Home > Net >  Creating multiple sublists in Python
Creating multiple sublists in Python

Time:01-02

I have a list J with len(J)=2. I want to create a sublist of each element in J[i] where i=0,1. I present the current and expected output.

J = [[1, 2, 4, 6, 7],[1,4]]
arJ1=[]

for i in range(0,len(J)):
    J1=[J[i]]
    arJ1.append(J1)
    J1=list(arJ1)
print("J1 =",J1)

The current output is

J1 = [[[1, 2, 4, 6, 7], [1, 4]]]

The expected output is

J1 = [[[1], [2], [4], [6], [7]], [[1], [4]]]

CodePudding user response:

you can try this,

J = [[1, 2, 4, 6, 7],[1,4]]
new_l = []
for l in J:
    tmp = []
    for k in l:
        tmp.append([k])
    new_l.append(tmp)

print(new_l)

this will give you [[[1], [2], [4], [6], [7]], [[1], [4]]]

CodePudding user response:

With simple list comprehension:

res = [[[i] for i in sub_l] for sub_l in J]
print(res)

[[[1], [2], [4], [6], [7]], [[1], [4]]]

CodePudding user response:

You can do in one line with list comprehension:

[[[k] for k in l] for l in J]

CodePudding user response:

J = [[1, 2, 4, 6, 7],[1,4]]
arJ1 = []

for in_list in J:
    new_list = []
    for x in in_list:
        new_list.append([x])
    arJ1.append(new_list)

print(arJ1)
  • Related