Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - manipulating lists to create another list

Tags:

python

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

like image 816
kd1978 Avatar asked Dec 07 '22 13:12

kd1978


2 Answers

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])
like image 73
Zaur Nasibov Avatar answered Dec 17 '22 19:12

Zaur Nasibov


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.

like image 23
Tim Pietzcker Avatar answered Dec 17 '22 20:12

Tim Pietzcker