Home > Mobile >  how to access and collect elements from a list in list?
how to access and collect elements from a list in list?

Time:07-06

This question is so simple, but the desired output is not clicking to me.

alist = [[0., 0., 0], [1 , 2, 3 ], [4, 5, 6 ],[7, 8, 9], [10, 11, 12], [13, 14, 15]]

a = []
for i in alist:
    for j in i:
        a.append(j[0:3])
print(a)

desired output :

a = [ [0, 1, 4, 7, 10, 13 ], [0, 2, 5, 8, 11, 14 ], [0, 3, 6, 9, 12, 15 ] ]

CodePudding user response:

You can use zip like zip(*alist) and get what you want, but if you want correct your code. you need enumerate.

>>> list(map(list, zip(*alist)))
[[0.0, 1, 4, 7, 10, 13], [0.0, 2, 5, 8, 11, 14], [0, 3, 6, 9, 12, 15]]

Your code:

a = [[],[],[]]                    # <- change this
for i in alist:
    for idx, j in enumerate(i):   # <- change this
        a[idx].append(j)          # <- change this
print(a)

Output:

[[0.0, 1, 4, 7, 10, 13], [0.0, 2, 5, 8, 11, 14], [0, 3, 6, 9, 12, 15]]

CodePudding user response:

You can just use list comprehension combined with zip and list unpacking:

>>> [list(x) for x in zip(*alist)]
#output:
# [[0.0, 1, 4, 7, 10, 13], [0.0, 2, 5, 8, 11, 14], [0, 3, 6, 9, 12, 15]]
  • Related