将随机选择附加到列表并仅打印随机选择

时间:2020-10-06 10:18:47

标签: python list random append

我对python真的很陌生,并且正在尝试创建一个小型ouija游戏。

我有一个数字列表,这些数字已经为我生成了一个随机选择 我想将该随机选择附加到一个空列表中,仅输出随机选择号 但是,当我运行代码时,它将输出原始列表中的所有内容,但是if else可以正常工作,如下所示,它可以输出正确的文本,但会列出原始列表中的每个数字

有人可以帮忙吗?

import random

#create list of random ages
age=["12,78,14,43,54,33,23,5,85,20,54,13"]

#user input
spirit2=input("Ask me how old I am: ")

#creat empty list of what will be the random age
agenum=[]

def checkage():

    #generate random age from the list age
    agespirit=random.choice(age)
    #append the random age to the to the agenum list
    agenum.append(agespirit)

    #print to terminal
    if "12"  in agespirit:
        print("I am only",agenum,"years old")
    else:
        print("I am",agenum,"years old")

checkage()

2 个答案:

答案 0 :(得分:1)

您有一个包含单个字符串的列表,而不是多个字符串的列表:

age=["12,78,14,43,54,33,23,5,85,20,54,13"]

您可以通过print(len(age))进行确认。

此列表包含一个大字符串。

您想要的是什么

age=["12","78","14","43","54","33","23","5","85","20","54","13"]

答案 1 :(得分:-1)

ages = [12,3,3,56,23,4]
# list of no. = ages
import random 
a = input("Ask me no. : ") # asked the user about the no. he want
b = []
c = random.choice(ages) # here I chosea random no. from ages == c and then stored that no. in b
b.append(c)
print(b)
if 12 in b:
  print(f'I am only {b} years old') # it was realy hard to get this output because of random function
else:
  print(f'I am  {b} year old')
# I hope this will help, I didn't create a function.