我有两个列表 - 让我们说一个游戏的每一轮获胜者之一,一个是获胜者的号码和相关名称。我希望在Python中尽可能简洁地打印出获奖者的名字。
现在,我的解决方案非常详细:
winners=[1, 2, 'NONE', 'NONE', 0]
ranking=[('Ron', 3), ('Brian', 4), ('Champ', 2), ('Brick', 0), ('Ed', 5), ('Veronica', 1)]
lastList=[]
for row in winners:
if row !="NONE":
for element in ranking:
if element[1]==row:
lastList.append(element[0])
else: lastList.append(row)
print lastList
['Veronica', 'Champ', 'NONE', 'NONE', 'Brick']
我尝试了单行简洁的if-then语句无济于事:
lastList=[[element[0] if element[1]==row for element in ranking] if row!="NONE" else row for row in winners]
我怀疑我在if-then单行语法中做错了什么。
答案 0 :(得分:2)
将排名变成dict:
people = {b: a for a, b in ranking}
people["NONE"] = "NONE"
last_list = [people[n] for n in winners]