简体   繁体   中英

Python - manipulating lists to create another list

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 (ie slide1) are created dynamically from the first list (list1).

ie 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!

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM