我有一個程序,有一個嵌套列表,我希望訪問,然後追加到基於條件的新列表。在每個列表中有三個列,我希望知道如何分別訪問它們。這是它目前的樣子[['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]
。一個更好解釋這個例子的例子是,如果我想從第二列中獲取數據,那麼我的新列表將看起來像['B', 'E', 'H']
。將嵌套列表值添加到一個新列表
這是我迄今爲止,但我現在寧願被卡住..
n = 0
old_list = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]
new_list = []
for a, sublist in enumerate(old_list):
for b, column in enumerate(sublist):
print (a, b, old_list[a][b])
if n == 0:
new_list.append(column[0])
if n == 1:
new_list.append(column[1])
if n == 2:
new_list.append(column[2])
print(new_list)
我的電流輸出..
0 0 A
0 1 B
0 2 C
1 0 D
1 1 E
1 2 F
2 0 G
2 1 H
2 2 I
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
我的期望輸出..
n = 0
new_list = ['A', 'D', 'G']
n = 1
new_list = ['B', 'E', 'H']
n = 2
new_list = ['C', 'F', 'I']
感謝您的幫助!
'*'代表什麼? – 2013-04-23 10:24:39
它解開列表到位置參數,一個很好的解釋是在這裏http://stackoverflow.com/questions/2921847/python-once-and-for-all-what-does-the-star-operator-mean-in- python – 2013-04-23 10:25:07
@StephaneRolland它被稱爲「splat」,它將'L'解包爲'zip'的參數 – jamylak 2013-04-23 10:25:39