您从我的作业中获得的代码是
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新手
答案 0 :(得分:3)
您的legislators
是dict
而不是list
。您可以访问keys
和values
:
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']
注意只有拥有python list
时才需要legislators.keys
致3.x
。对于python 2.x
,没有必要。
修改强>
正如@Frerich Raabe在评论中建议的那样,你可以使用set
来获得如下的独特派对:
parties = set(legislators.values())
print(parties)
{'DAB', 'Democratic', 'Economic Synergy', 'Labour'}
或者如果您想要列表作为结果:
print(list(set(legislators.values())))
['Democratic', 'Labour', 'Economic Synergy', 'DAB']
答案 1 :(得分: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']
答案 2 :(得分:0)
使用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')