0

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]]]
1
  • 7
    [[[j] for j in i] for i in J] Commented Jan 2, 2023 at 6:29

4 Answers 4

1

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]]]

Sign up to request clarification or add additional context in comments.

Comments

1

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]]]

Comments

1

You can do in one line with list comprehension:

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

Comments

1
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.