如何使用for循环比较Python中的两个列表?

2024-06-01 06:12:12 发布

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

我正在做一个练习,要求我完成以下任务。我在第三个堆栈中:

  1. 创建两个变量,称为甘道夫和萨鲁曼,并为它们分配法术能力列表。创建一个名为spells的变量来存储巫师施放的法术数量

    spells = 10
    gandalf = [10, 11, 13, 30, 22, 11, 10, 33, 22, 22]
    saruman = [23, 66, 12, 43, 12, 10, 44, 23, 12, 17]
    
  2. 创建两个变量,称为gandalf_wins和saruman_wins。将两者都设置为0。 您将使用这些变量来计算每个巫师赢得的冲突数量

    gandalf_wins=0
    saruman_wins=0
    
  3. 使用两个巫师的法术列表,更新变量gandalf_wins和saruman_wins,计算每个巫师赢得冲突的次数

我的解决方案是,但不是比较列表中的所有元素,你能帮我吗

for spells in saruman, gandalf:
    if gandalf>saruman:
        gandalf_wins += 1
    elif saruman>gandalf:
        saruman_wins += 1

print("Total gandalf wins:", gandalf_wins)
print("Total saruman wins:", saruman_wins)

Tags: 元素列表for数量堆栈能力解决方案次数
2条回答

问题在于for循环的定义方式。您应该迭代列表中的元素,然后比较它们

for s, g in zip(saruman, gandalf):
    if g>s:
        gandalf_wins += 1
    elif s>g:
        saruman_wins += 1

您可以使用zip()创建成对的法术,以便轻松比较它们:

gandalf_wins=0
saruman_wins=0

gandalf = [10, 11, 13, 30, 22, 11, 10, 33, 22, 22]
saruman = [23, 66, 12, 43, 12, 10, 44, 23, 12, 17]

for spells in zip(saruman, gandalf):
    # iterations look like: [(10, 23), (11, 66), (13, 12)...]
    gandalf_spell_power = spells[0]
    saruman_spell_power = spells[1]

    if gandalf_spell_power>saruman_spell_power:
        gandalf_wins += 1
    elif saruman_spell_power>gandalf_spell_power:
        saruman_wins += 1

print("Total gandalf wins:", gandalf_wins)
print("Total saruman wins:", saruman_wins)

输出:

('Total gandalf wins:', 4)
('Total saruman wins:', 6)

相关问题 更多 >