如何在此词典中使用if语句

时间:2016-07-22 18:22:51

标签: python-3.x if-statement dictionary

这是我的代码

players = []
while len(players) >= 0:
    name = input('Enter a name: ')
    players.append(name)
    if name == '':
        players.pop()
        break
    else:
        pass             

player_dict = {name: [] for name in players}
print(player_dict)

for name in player_dict:
    answer = input(name + ', who will win the fight? ')
    player_dict[name].append(answer)

fight_winner = input('Who won the fight? ')

for name in player_dict:
    if answer == fight_winner:
        print(name + ' = Correct')
    else:
        print(name + ' = Incorrect')
print(player_dict)

这是我在运行代码时看到的内容

Enter a name: bill
Enter a name: bob
Enter a name: 
{'bill': [], 'bob': []}
bill, who will win the fight? red
bob, who will win the fight? blue
Who won the fight? red
bill = Incorrect
bob = Incorrect
{'bill': ['red'], 'bob': ['blue']}

我希望看到bill = Correct。如何访问每个indivuals值并通过if语句运行它?感谢您的帮助

2 个答案:

答案 0 :(得分:1)

更改

getattr(self.MyQThread, 'signal' + str(n)).emit(value)

要:

for name in player_dict:
    if answer == fight_winner:
        print(name + ' = Correct')
    else:
        print(name + ' = Incorrect')
print(player_dict)

您的for name, colors in player_dict.items(): if fight_winner in colors: print(name + ' = Correct') else: print(name + ' = Incorrect') print(player_dict) 是名称以外的颜色。您将颜色存储到列表中,如下所示:

player_dict [名称] .append(回答)

键是name,值是颜色列表。因此,当您迭代字典fight_winner时,您应该找到基于颜色player_dict的{​​{1}}

你不能在条件语句name中使用变量答案,原因是答案的值总是由最后一次迭代分配,并且它可能没有给你正确的比较。

例如,如果订单为蓝色然后是红色,则答案为红色,并且您将fight_winner设置为蓝色,两个玩家都为if answer == fight_winner:

以下是我的测试:

fight_winner

答案 1 :(得分:0)

在目前的表单中,您可以通过更改以下内容来使代码正常工作:

if answer == fight_winner:

到:

if player_dict[name][0] == fight_winner:

或(甚至更好):

answer = player_dict[name][0]
if answer == fight_winner:

但是,我不认为每个玩家的词典条目都需要列表,因为您只为每个玩家存储单个值。请考虑使用以下内容:

player_dict = {}

for name in players:
    answer = input(name + ', who will win the fight? ')
    player_dict[name] = answer

fight_winner = input('Who won the fight? ')

for name, answer in player_dict:
    if answer == fight_winner:
        print(name + ' = Correct')
    else:
        print(name + ' = Incorrect')

这种方法似乎更具可读性(至少在我看来),并且不使用player_dict中的列表,因为它们不是必需的(在当前的代码形式中)。