如何在python中从i in range中的输入中获取随机项

t1rydlwq  于 2022-12-02  发布在  Python
关注(0)|答案(3)|浏览(135)

我正在做一个程序,它会询问有多少玩家在玩游戏,然后询问玩家的名字。我想让它打印一个随机的玩家,但不知道怎么做。代码现在打印一个随机的字母,从最后一个名字给我想

import random
player_numberCount = input("How many players are there: ")
player_number = int(player_numberCount)

for i in range(player_number):
    ask_player = input("name the players: ")

print(random.choice(ask_player))
s3fp2yjn

s3fp2yjn1#

您需要将输入的每个玩家名称添加到列表中。下面是您在代码中需要的起点:

from random import choice

number_of_players = int(input("How many players are there: "))
players = []

for _ in range(number_of_players):
    players.append(input("name the players: "))

print(choice(players))
ffx8fchx

ffx8fchx2#

问题在于,在每次for循环迭代中,你都要将ask_player变量重新分配给一个字符串。当你将一个字符串传递给random.choice(...)时,它会从该字符串中随机选取一个字母(因为字符串可以像数组一样被索引)。只需在循环前定义一个数组,并在每次迭代时追加:

import random

player_numberCount = input("How many players are there: ")
player_number = int(player_numberCount)

players = []
for i in range(player_number):
    players.append(input(f"name player {i + 1}: "))

print(random.choice(players))
hpxqektj

hpxqektj3#

该循环在每次迭代时重新分配ask_player变量,擦除先前的值。
您可能希望将每个值保存在一个列表中:

players = []
for i in range(player_number):
    players.append(input("Player name: "))

print(random.choice(players))

相关问题