将列表元素分配给 For 循环中的字符串

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


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


天涯尽头无女友
浏览 124回答 3
3回答

慕森卡

i返回一个介于 1 和 4 之间的值,这就是您遇到list assignment index out of range错误的原因。你可以只列出一个项目:items&nbsp;=&nbsp;["rock","scissors","paper"]并随机选择它们players&nbsp;=&nbsp;[items[np.random.randint(1,&nbsp;4)],&nbsp;items[np.random.randint(1,&nbsp;4)]]

智慧大石

i是列表中该元素的值,而不是索引。如果您想更改列表而不是使用索引进行迭代。for indx, val in enumerate(players):&nbsp; &nbsp; if val == 1:&nbsp; &nbsp; &nbsp; &nbsp; players[indx] = 'rock'&nbsp; &nbsp; elif val == 2:&nbsp; &nbsp; &nbsp; &nbsp; players[indx] = 'scissors'&nbsp; &nbsp; elif val == 3:&nbsp; &nbsp; &nbsp; &nbsp; players[indx] = 'paper'你也不需要使用像 NumPy 这样的大包来获取一些随机数,因为 python 有一个内置的方法来做到这一点:import randomchoices = [random.randint(0, 2) for _ in range(2)]print(choices) # [0, 2]您也可以random充分利用:import randomCHOICES = ('rock', 'paper', 'scissors')choice1 = random.choice(CHOICES)choice2 = random.choice(CHOICES)print(choice1, choice2) # rock paper

小唯快跑啊

使用len列表的属性进行迭代for i in range(len(players)):&nbsp; &nbsp; if players[i] == 1:&nbsp; &nbsp; &nbsp; &nbsp; players[i] = 'rock'&nbsp; &nbsp; elif players[i] == 2:&nbsp; &nbsp; &nbsp; &nbsp; players[i] = 'scissors'&nbsp; &nbsp; elif players[i] == 3:&nbsp; &nbsp; &nbsp; &nbsp; players[i] = 'paper'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python