Reputation: 6149
I have two lists -- let's say one of the winners of each round of a game, and one is the winner's number, and associated name. I'm looking to print out the names of the winners as concisely as possible in Python.
Right now, my solution is quite verbose:
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']
I tried a single-line concise if-then statement to no avail:
lastList=[[element[0] if element[1]==row for element in ranking] if row!="NONE" else row for row in winners]
My suspicion is that I'm doing something wrong in the if-then single-line syntax.
Upvotes: 0
Views: 53
Reputation: 225263
Turn the ranking into a dict:
people = {b: a for a, b in ranking}
people["NONE"] = "NONE"
last_list = [people[n] for n in winners]
Upvotes: 2