2016-02-17 198 views
0

嗨,我已經從我的任務給予代碼的特定元素的列表是創建從字典

legislators = { "Tsang Yok-sing" : "DAB", "Albert Ho" : "Democratic", "Lee Cheuk-yan" : "Labour", "James To" : "Democratic", "Chan Kam-lam" : "DAB", "Lau Wong-fat" : "Economic Synergy", "Emily Lau" : "Democratic" } 

我需要創建兩個列表,一個只有立法者的名字和其他與列表的派對。我不明白列表之間的冒號意味着什麼,我猜它以某種方式連接了這兩個冒號。真的很欣賞一些指導。

欣賞雅爸爸愛

對不起,我的錯,這是人提到一本字典。 Python新手

+5

這不是一個列表,這是一個字典。冒號意味着元素之間的鍵 - >值關係 –

+0

哦,我明白了。謝謝我會在Google上查看這些內容! –

+0

它的一個字典與鍵:值對 –

回答

3

您的legislatorsdict不是list。你可以訪問keysvalues

names = list(legislators.keys()) 
parties = list(legislators.values()) 

print(names) 
['Tsang Yok-sing', 'Lee Cheuk-yan', 'James To', 'Chan Kam-lam', 'Lau Wong-fat', 'Emily Lau', 'Albert Ho'] 

print(parties) 
['DAB', 'Labour', 'Democratic', 'DAB', 'Economic Synergy', 'Democratic', 'Democratic'] 

需要調用listlegislators.keys只有當你有蟒蛇3.x。對於python 2.x這沒有必要。

編輯

由於@Frerich拉貝在評論所說,你可以使用set獲得獨特的各方,如:

parties = set(legislators.values()) 

print(parties) 
{'DAB', 'Democratic', 'Economic Synergy', 'Labour'} 

或者,如果你想列表作爲結果:

print(list(set(legislators.values()))) 
['Democratic', 'Labour', 'Economic Synergy', 'DAB'] 
+3

你可能想使用'set()'而不是'list()'擺脫'締約方'中的重複。 –

+0

正是我所需要的,非常感謝你 –

+1

@FrerichRaabe是啊,如果OP感興趣的獨特價值可以用'set'完成 –

0

你在那裏有一本字典。

你可以把它分成兩個表是這樣的:

legislators = { "Tsang Yok-sing" : "DAB", "Albert Ho" : "Democratic", "Lee Cheuk-yan" : "Labour", "James To" : "Democratic", "Chan Kam-lam" : "DAB", "Lau Wong-fat" : "Economic Synergy", "Emily Lau" : "Democratic" } 

names = [] 
parties = [] 

for item in legislators: 
    names.append(item) 
    parties.append(legislators[item]) 

print names, parties 

會導致

['Tsang Yok-sing', 'Emily Lau', 'Lau Wong-fat', 'Chan Kam-lam', 'James To', 'Albert Ho', 'Lee Cheuk-yan'] 
['DAB', 'Democratic', 'Economic Synergy', 'DAB', 'Democratic', 'Democratic', 'Labour'] 
0

易oneliner使用zip(*legislators.items())

In[2]: legislators = { "Tsang Yok-sing" : "DAB", "Albert Ho" : "Democratic", "Lee Cheuk-yan" : "Labour", "James To" : "Democratic", "Chan Kam-lam" : "DAB", "Lau Wong-fat" : "Economic Synergy", "Emily Lau" : "Democratic" } 
In[3]: names, parties = zip(*legislators.items()) 
In[4]: names 
Out[4]: 
('Tsang Yok-sing', 
'Emily Lau', 
'Lau Wong-fat', 
'Chan Kam-lam', 
'James To', 
'Albert Ho', 
'Lee Cheuk-yan') 
In[5]: parties 
Out[5]: 
('DAB', 
'Democratic', 
'Economic Synergy', 
'DAB', 
'Democratic', 
'Democratic', 
'Labour')