Skip to content
Advertisement

is it possible to generate a list in list for desired numbers?

I wanted to generate a list in list :

now, I have basically two options, either I input the list through a text file or I should generate the list by itself.

is it possible to generate this type of list by itself using nested loops?

[[0,0,0], [0,0,0] ,[0,0,0], [0,0,0,], [0,0,0]]


I wanted to put -1 at the place of the middle zero of each sub-list like [0, -1, 0], there are 5 sub-list so the -1 should be inserted 5 times

so desired result would be

[[0,-1,0], [0,0,0] ,[0,0,0], [0,0,0,], [0,0,0]]
[[0,0,0], [0,-1,0] ,[0,0,0], [0,0,0,], [0,0,0]]
[[0,0,0], [0,0,0] ,[0,-1,0], [0,0,0,], [0,0,0]]
[[0,0,0], [0,0,0] ,[0,0,0], [0,-1,0,], [0,0,0]]
[[0,0,0], [0,0,0] ,[0,0,0], [0,0,0,], [0,-1,0]]


In my actual work, I have 38 sub-lists, for convenience, I showed only 5 here.

my attempt –

presently I am doing this by using json.loads and inputting this as a dictionary then collecting it using append and further converting it into a list and then I’ll use those values. however, this method seems so cumbersome to me.

F = []
import json
with open('unitvalue.txt') as f:  
        f_1 =   {int(key): json.loads(val) for key, val in json.loads(f.readline()).items()}
        f_2 =   {int(key): json.loads(val) for key, val in json.loads(f.readline()).items()}
        f_3 =   {int(key): json.loads(val) for key, val in json.loads(f.readline()).items()}
        f_4 =   {int(key): json.loads(val) for key, val in json.loads(f.readline()).items()}
        f_5 =   {int(key): json.loads(val) for key, val in json.loads(f.readline()).items()}


where unitvalue.txt contain

{"1":"[0,-1,0]", "2":"[0,0,0]","3":"[0,0,0]", "4":"[0,0,0]", "5":"[0,0,0]"}
{"1":"[0,0,0]", "2":"[0,-1,0]","3":"[0,0,0]", "4":"[0,0,0]", "5":"[0,0,0]"}
{"1":"[0,0,0]", "2":"[0,0,0]","3":"[0,-1,0]", "4":"[0,0,0]", "5":"[0,0,0]"}
{"1":"[0,0,0]", "2":"[0,0,0]","3":"[0,0,0]", "4":"[0,-1,0]", "5":"[0,0,0]"}
{"1":"[0,0,0]", "2":"[0,0,0]","3":"[0,0,0]", "4":"[0,0,0]", "5":"[0,-1,0]"}


Advertisement

Answer

You can do it with a list comprehension:

n = 5
[[[0, -1, 0] if i == j else [0, 0, 0] for j in range(n)] for i in range(n)]

Output:

[[[0, -1, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
 [[0, 0, 0], [0, -1, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
 [[0, 0, 0], [0, 0, 0], [0, -1, 0], [0, 0, 0], [0, 0, 0]],
 [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, -1, 0], [0, 0, 0]],
 [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, -1, 0]]]

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement