如何从2个列表和Python中的其他词典创建词典?

2024-06-01 07:03:00 发布

您现在位置:Python中文网/ 问答频道 /正文

回答here

1.首先我创建了变量POWERgandalfsaruman,如上面代码中所示,然后创建了一个名为spells的变量来存储巫师施放的法术数量

代码

POWER = {
    'Fireball': 50, 
    'Lightning bolt': 40, 
    'Magic arrow': 10, 
    'Black Tentacles': 25, 
    'Contagion': 45
}

gandalf = ['Fireball', 'Lightning bolt', 'Lightning bolt', 'Magic arrow', 'Fireball', 
           'Magic arrow', 'Lightning bolt', 'Fireball', 'Fireball', 'Fireball']
saruman = ['Contagion', 'Contagion', 'Black Tentacles', 'Fireball', 'Black Tentacles', 
           'Lightning bolt', 'Magic arrow', 'Contagion', 'Magic arrow', 'Magic arrow']
spells=10

  1. 然后创建了两个变量,称为甘道夫赢和萨鲁曼赢。将两者都设置为0
gandalf_wins=0
saruman_wins=0
  1. 最后两个变量称为甘道夫力量和萨鲁曼力量,用于存储每个巫师的法术力量列表
gandalf_power=[]
saruman_power=[]
  1. 战斗开始了!使用上面创建的变量,对拼写冲突的执行进行编码。请记住,如果一个巫师连续成功赢得3次法术冲突,他将获胜。 如果冲突以平局结束,则连续获胜的计数器不会重新启动为0。记住打印谁是战斗的胜利者

我在这里被绊住了,因为我不知道如何为每一个单词创建一本字典,里面都有拼写和拼写的力量。那么,我应该如何比较它们呢?提前谢谢


Tags: 代码magicblacklightningpower力量boltgandalf
3条回答

我认为这些步骤说明得非常清楚,使用for循环就足以解决第三部分

对于第四部分,您可以使用zip,同时对这两个列表进行整理

for gandalf_pow, saruman_pow in zip(gandalf_power, saruman_power):
    # compare

下面是使用zip来循环法术,并比较每轮法术的威力

POWER = {
    'Fireball': 50, 
    'Lightning bolt': 40, 
    'Magic arrow': 10, 
    'Black Tentacles': 25, 
    'Contagion': 45
}

gandalf = ['Fireball', 'Lightning bolt', 'Lightning bolt', 'Magic arrow', 'Fireball', 'Magic arrow', 'Lightning bolt', 'Fireball', 'Fireball', 'Fireball']
saruman = ['Contagion', 'Contagion', 'Black Tentacles', 'Fireball', 'Black Tentacles', 'Lightning bolt', 'Magic arrow', 'Contagion', 'Magic arrow', 'Magic arrow']
spells=10

gandalf_wins=0
saruman_wins=0

for gandalf_spell, saruman_spell in zip(gandalf,saruman): 
    if POWER[gandalf_spell] > POWER[saruman_spell]: 
        gandalf_wins+=1 
    elif POWER[saruman_spell] > POWER[gandalf_spell]: 
        saruman_wins+=1 

print(f"Gandalf won {gandalf_wins} times, Saruman won {saruman_wins} times")

您应该参考Python字典。它们就像列表和元组,只是不同之处在于它们就像数据库的表,其中有用于存储不同值的行和列

https://www.w3schools.com/python/python_dictionaries.asp 请参阅此以获取帮助

相关问题 更多 >