Reputation: 511
I have a number of lists that are of equal length, say 4, but this can change. What I want to do is combine these lists, so that the first item of each list, item[0], is combined to form a new list. Similarly with item[1], item[2] etc. This seems simple enough, but how do I make sure that the list names (i.e. slide1) are created dynamically from the first list (list1).
i.e. I want to go from this:
list1 = ['slide1','slide2','slide3','slide4']
list2 = [1,2,3,4]
list3 = ['banana', 'apple', 'pear', 'orange']
to this:
slide1 = ['slide1',1,'banana']
slide2 = ['slide2',2,'apple']
slide3 = ['slide3',3,'pear']
slide4 = ['slide4',4,'orange']
The reason I need to do this is to then subsequently enter these lists into a database. Any clues? I think I know how to do the for loop, but am stuck with the creation of 'dynamic' list names. Should I otherwise use a dictionary?
Thanks in advance for the help!
Upvotes: 4
Views: 888
Reputation: 82765
Using itertools.izip
will be more efficient if the list is very large and you just need to iterate through the new slides.
import itertools
for x in itertools.izip(list1, list2, list3):
print x
Upvotes: 1
Reputation: 142146
A direct answer is that it seems you want a dict
with the list1 element as a key which can be achieved as follows:
dict( zip(list1, list(zip(list2, list3))) )
However, Tim's correct in saying you should review your data structure...
Upvotes: 1
Reputation: 336148
You don't want to create variable names on-the-fly.
In fact, you shouldn't be having list1, list2, list3
in the first place but rather a single list called lists
:
>>> lists = [['slide1','slide2','slide3','slide4'], [1,2,3,4], ['banana', 'apple', 'pear', 'orange']]
>>> slides = [list(slide) for slide in zip(*lists)]
>>> slides
[['slide1', 1, 'banana'], ['slide2', 2, 'apple'], ['slide3', 3, 'pear'], ['slide4', 4, 'orange']]
Now, instead of list1
, you use lists[0]
, and instead of slide1
, you use slides[0]
. This is cleaner, easier to maintain, and it scales.
Upvotes: 3
Reputation: 22659
Very simple:
lst = zip(list1, list2, list3)
print(lst[0])
>>> ('slide1', 1, 'banana')
# in case you need a list, not a tuple
slide1 = list(lst[0])
Upvotes: 10