1

Imagine my old list is:

old = [[card, towel, bus], [mouse, eraser, laptop], [pad, pen, bar]]

goal:

new = [[card, mouse, pad], [towel, eraser, pen], [bus, laptop, bar]]

Things I've tried:

new = dict(zip(old[i] for i in range(len(old))))

new = [old[i][0] for i in old] #trying just to get a list of first indices, and then go from there

I feel like this is a trivial problem, but I'm having trouble. Thanks in advance for pointing me in the right direction!

Also: Imagine I have another list:

list_names = ['list1', 'list2', 'list3']

I would like to set the elements of this list to each one of the new lists:

list1 = [card, mouse, pad] 

and so on.

Any ideas?

a bus
  • 11
  • 2
  • 2
    Possible duplicate of [Transpose a matrix in Python](http://stackoverflow.com/questions/17037566/transpose-a-matrix-in-python) – awesoon Aug 12 '16 at 15:54
  • For your second question, this would be doing dynamic variable lookup, which is probably not a good idea. Could be achieved with `lists = [locals()[name] for name in list_names]`. – pistache Aug 12 '16 at 15:58

3 Answers3

2

For your first question, this is the basic usage of zip:

>>> old = [['card', 'towel', 'bus'], ['mouse', 'eraser', 'laptop'], ['pad', 'pen', 'bar']]
>>> zip(*old)
[('card', 'mouse', 'pad'), ('towel', 'eraser', 'pen'), ('bus', 'laptop', 'bar')]

I can't understand your second question.

wim
  • 338,267
  • 99
  • 616
  • 750
0

Method 1: If you want reach your first goal in one line and want to use list comprehensions try:

old = [[1,2,3],[4,5,6],[7,8,9]]
new = [[sublist[i] for sublist in old ] for i in (0,1,2)]

leads to new = [[1, 4, 7], [2, 5, 8], [3, 6, 9]].

Method 2: However you can also use the zip-function like this:

new = [list for list in zip(*old)]

will lead to new = [(1, 4, 7), (2, 5, 8), (3, 6, 9)]. Note that this is a list of tuples as opposed to the first example.

0

Thanks so much for the input everyone! zip(*old) worked like a charm, though I'm not entirely sure how...

For the second problem, I used this: (I know this is not a good solution, but it worked)

for name in range(input_num):
    exec(list_names[name] + ' = arranged_list[name]')
a bus
  • 11
  • 2