python3 - 列表转换为 int,我如何 return 将其转换为 int 之前的原始值

python3 - list converted to int, how do I return it to it's original value before the int

我正在尝试编写一个程序来 select 从名称列表中随机选择一个名称。 selected 的人必须支付每个人的伙食费。我不知道如何将名称转换回用户的原始输入。如果有更清洁的方法可以做到这一点,请告知。提前谢谢大家。示例如下:

names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
names = len(names)
names = random.randint(0, 4)
if names == 0:
    print(f"{names} is going to buy the meal today!")
elif names == 1:
    print(f"{names} is going to buy the meal today!")
elif names == 2:
    print(f"{names} is going to buy the meal today!")
else:
    print(f"{names} is going to buy the meal today!")

注意不要重新分配 names 标识符,因为您会丢失先前操作的结果。您可以使用 list[index] 语法(称为订阅)获取给定索引处的列表元素:

names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
random_name = names[random.randint(0, len(names))]
print(f"{random_name} is going to buy the meal today!")

您也可以使用 random.choice 进行随机选择,而不必担心索引。

names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
random_name = random.choice(names)
print(f"{random_name} is going to buy the meal today!")

你可以试试下面的代码,在随机方法returns之后显示出要买饭的人的名字一个值。

# get the input names of friends separated by comma
names=input("Enter the names of every person separated by a comma")
# get the list of names by splitting the string above using the comma delimiter
name_collection=names.split(",")
# get the random index of the person who is going to pay for the bills
choice=random.randint(0,len(name_collection))
#print the name of the person who is going to buy the meal
print(name_colection[choice])