2016-08-12 25 views
1

想象我的舊名單相同的指標是:我有一個列表的列表。我想提出名單的一個新的列表,但每個新列表都會有老的名單

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

目標:

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

事情我已經嘗試:

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 

我覺得這是一個微不足道的問題,但我有麻煩。提前感謝您指點我正確的方向!

另外: 想象我有另外一個列表:

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

我想這個列表的內容設置爲新列表的每一個:

​​

等。

任何想法?

+2

的[移調在Python矩陣(http://stackoverflow.com/questions/17037566/transpose-a-matrix-in-python) – soon

+2

新=拉鍊(*舊) – Julien

+0

關於第二個可能的複製問題,這將做動態變量查找,這可能不是一個好主意。可以用'list = [locals()[name] for list_names]''來實現。 – pistache

回答

3

關於第一個問題,這是zip的基本用法:

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

我不明白你的第二個問題。

0

方法1:如果你想在一行達到你的第一個目標,並希望使用列表理解嘗試:

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

導致new = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

方法2:然而,你也可以使用zip -function是這樣的:

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

會導致new = [(1, 4, 7), (2, 5, 8), (3, 6, 9)]。請注意,這是與第一個示例相反的元組列表。

0

非常感謝大家的意見! ZIP(*舊)工作就像一個魅力,雖然我不能完全肯定

對於第二個問題是如何......,我用這個(我知道這是不是一個很好的解決方案,但它的工作)

for name in range(input_num): 
    exec(list_names[name] + ' = arranged_list[name]') 
相關問題