简体   繁体   English

如何从输入列表中随机选择一个项目?

[英]How to pick a random item from an input list?

I am making a program that asks how many players are playing, and then asks to input the names of those players.我正在制作一个程序,询问有多少玩家在玩,然后要求输入这些玩家的名字。 Then, I want it to print a random player, but I can't figure it out how.然后,我想让它打印一个随机播放器,但我不知道怎么做。

The code right now prints a random letter from the last name given, I think:现在的代码从给定的姓氏中随机打印一个字母,我认为:

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))

You need to add each player name entered to a list.您需要将输入的每个玩家名称添加到列表中。 Here is a starting point of what you need in your code:这是您在代码中需要的起点:

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))

That loop reassigns the ask_player variable on each iteration, erasing the previous value.该循环在每次迭代时重新分配ask_player变量,擦除先前的值。

Presumably you meant to save each value in a list:大概您打算将每个值保存在列表中:

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

print(random.choice(players))

The problem is that in each for-loop iteration, you are reassigning the ask_player var to a string.问题是在每次 for 循环迭代中,您都将 ask_player var 重新分配给一个字符串。 When you pass a string to random.choice(...), it picks a random letter of that string (since strings can be indexed like arrays).当您将一个字符串传递给 random.choice(...) 时,它会选择该字符串的一个随机字母(因为字符串可以像数组一样被索引)。 Just define an array before the loop and append on each iteration:只需在循环之前定义一个数组,并在每次迭代中定义 append:

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))
import random

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


for _ in range(player_number):
    ask_player = input("name the players: ")
    player_list.append(ask_player)

print(player_list[random.randint(0, player_number)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM