0

I have a list of lists (will grow) and I don't know how many elements it has, but all the lists will have all the time the same lenth of elements.

For example if I have:

new=[]
new.append(users)
new.append(users_count)
new.append(users_avg)
print(new)

lst2 = [item[0] for item in new]
print(lst2)

In this case the output will be:

[['ser', 'admin', 'emma', 'paul'], [2, 10, 5, 9], [33, 37, 16, 67]]
['ser', 2, 33]

What it is correct, but I would like to get:

['ser', 2, 33]
['admin', 10, 37]
['emma', 5, 16]
['paul', 9, 67]

i.e the first value of each of the lists in a new list, the second value of each list, the third value of each list and so on (always will be three lists but the elements inside will grow).

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
serlomu
  • 21
  • 1
  • 4

3 Answers3

1

The builtin zip function is what you are looking for:

users = ['ser', 'admin', 'emma', 'paul']
users_count = [2, 10, 5, 9]
users_avg = [33, 37, 16, 67]

user_tuples = [*zip(users, users_count, users_avg)]

print(user_tuples)

Output:

[('ser', 2, 33), ('admin', 10, 37), ('emma', 5, 16), ('paul', 9, 67)]
Fractalism
  • 1,231
  • 3
  • 12
1

you basically want to transpose your nested list. one way to do that is:

lst = [['ser', 'admin', 'emma', 'paul'], [2, 10, 5, 9], [33, 37, 16, 67]]

transposed = list(zip(*lst))
print(transposed)
# [('ser', 2, 33), ('admin', 10, 37), ('emma', 5, 16), ('paul', 9, 67)]

note that the inner sequences are tuples now and not lists.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
0

You can use a list comprehension with zip.

res = [[*x] for x in zip(*new)]
# [['ser', 2, 33], ['admin', 10, 37], ['emma', 5, 16], ['paul', 9, 67]]
Unmitigated
  • 76,500
  • 11
  • 62
  • 80