Populating a list with items from different lists in Python
I want to create a list by reading information from other lists. The list will have a form maindot =[dot1[0], dot2[0], ...]
containing information from lists dot1
etc, for example.
dot1=[2,4,34], dot2=[3,45,4],
which will be in a separate parameter file. The number of dotted lists will be specified by the user as n.
How do I write so that python "knows" the number of dotted lists given in the options file?
source to share
You can use a function zip
to get columns from an arbitrary number of iterations:
>>> dot1=[2,4,34]
>>> dot2=[3,45,4]
>>> zip(dot1,dot2)
[(2, 3), (4, 45), (34, 4)]
And you want to put the first index of your lists in another list, you can just get the first index zip(dot1,dot2)
:
new_list=zip(dot1,dot2)[0]
Note that in python 3 it zip
returns a generator so you can use a function next
to access the first index:
new_list=next(zip(dot1,dot2))
And if you have a lot of list, you can put all of them in a list and pass them all by unpacking the operation to a function zip
:
new_list=zip(*main_list)[0]
source to share