【问题标题】:Assigning List Element to a String in a For Loop将列表元素分配给 For 循环中的字符串
【发布时间】:2019-08-09 18:50:59
【问题描述】:

我正在尝试遍历列表中的两个元素(整数),并且对于列表中的每个元素,如果值等于整数,我想用字符串替换元素。我做错了什么?

players = [np.random.randint(1, 4), np.random.randint(1, 4)]

for i in players:
    if i == 1:
        players[i] = 'rock'
    elif i == 2:
        players[i] = 'scissors'
    elif i == 3:
        players[i] = 'paper'

player_1 = players[0]
computer = players[1]

print(player_1)
print(computer)
Actual:

scissors
1

or, I get this error:

Traceback (most recent call last):
enter Player 1's choice:
  File "...", line 12, in <module>
    players[i] = 'scissors'
enter Player 2's choice:
IndexError: list assignment index out of range


Expected

scissors
rock

【问题讨论】:

  • i 不是索引,它实际上是列表中的元素。尝试枚举或简单地使用range(len(players)) 而不是players

标签: python python-3.x list loops


【解决方案1】:

i 返回一个介于 1 和 4 之间的值,这就是出现 list assignment index out of range 错误的原因。

你可以只列出一个项目:

items = ["rock","scissors","paper"]

并随机选择它们

players = [items[np.random.randint(1, 4)], items[np.random.randint(1, 4)]]

【讨论】:

    【解决方案2】:

    i 是列表中该元素的值,而不是索引。如果您想更改列表而不是使用索引进行迭代。

    for indx, val in enumerate(players):
        if val == 1:
            players[indx] = 'rock'
        elif val == 2:
            players[indx] = 'scissors'
        elif val == 3:
            players[indx] = 'paper'
    

    另外,你不需要使用像 NumPy 这样的大包来获取一些随机数,因为 python 有一个内置的方法来做到这一点:

    import random
    choices = [random.randint(0, 2) for _ in range(2)]
    print(choices) # [0, 2]
    

    您也可以充分利用random

    import random
    CHOICES = ('rock', 'paper', 'scissors')
    choice1 = random.choice(CHOICES)
    choice2 = random.choice(CHOICES)
    print(choice1, choice2) # rock paper
    

    【讨论】:

      【解决方案3】:

      使用列表的len属性进行迭代

      for i in range(len(players)):
          if players[i] == 1:
              players[i] = 'rock'
          elif players[i] == 2:
              players[i] = 'scissors'
          elif players[i] == 3:
              players[i] = 'paper'
      

      【讨论】:

        猜你喜欢
        • 2011-09-11
        • 1970-01-01
        • 2016-04-21
        • 2020-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-24
        • 2023-01-25
        相关资源
        最近更新 更多