如果在for中找到,则Python.append不起作用
使用列表创建者为音响团队生成任务。创建4个列表,并根据他们接受的培训和他们能够从事的工作,将人员添加到各种列表中。我有一个包含所有人的基本列表。.append适用于该列表,但对于具有条件的所有列表,名称都不会追加 我试着将我的for-str-in-addto改成其他东西,但到目前为止没有任何效果如果在for中找到,则Python.append不起作用,python,string,list,input,append,Python,String,List,Input,Append,使用列表创建者为音响团队生成任务。创建4个列表,并根据他们接受的培训和他们能够从事的工作,将人员添加到各种列表中。我有一个包含所有人的基本列表。.append适用于该列表,但对于具有条件的所有列表,名称都不会追加 我试着将我的for-str-in-addto改成其他东西,但到目前为止没有任何效果 my_list = [] stage_list = [] mic_list = [] all_list = [] def addto_list(): addto = input() f
my_list = []
stage_list = []
mic_list = []
all_list = []
def addto_list():
addto = input()
for str in addto:
input("Can he do stage?(y/n): ")
if input == "y":
stage_list.append(addto)
else:
break
for str in addto:
input("Can he do mic?(y/n): ")
if input == "y":
mic_list.append(addto)
else:
break
for str in addto:
input("Can he do sound?(y/n): ")
if input == "y":
all_list.append(addto)
else:
break
my_list.append(addto)
我想要的结果是,当我为任何条件语句回答y时,名称将附加到列表中。但当我这样做时,列表仍然显示为空白。例如,我运行代码
addto_list()
Input: Jack
Can he do stage: y
can he do mic: y
can he do sound: y
print(my_list)
return: Jack
print(mic_list)
return: [] blank when it should say Jack
您需要将
输入设置为一行:
my_list = []
stage_list = []
mic_list = []
all_list = []
def addto_list():
addto = input()
for str in addto:
if input("Can he do stage?(y/n): ") == "y":
stage_list.append(addto)
else:
break
for str in addto:
if input("Can he do mic?(y/n): ") == "y":
mic_list.append(addto)
else:
break
for str in addto:
if input("Can he do sound?(y/n): ") == "y":
all_list.append(addto)
else:
break
my_list.append(addto)
您的代码不起作用,因为您输入了
,但随后您丢失了对象,因为您没有分配变量,也没有在任何地方使用它。OTOHinput
是一个关键字,它是
,因此它肯定不是“y”尝试将y/n分配给变量,而不是直接使用输入。像
阶段=输入(“他能做阶段吗?(y/n):”)
如果Stage==“y”:请尝试此方法<代码>输入
不应用作变量。而且,不需要for循环。在这种情况下,它将接收每个字母(ja C K),并要求提供舞台、麦克风和声音
my_list = []
stage_list = []
mic_list = []
all_list = []
def addto_list():
global stage_list, my_list, mic_list, all_list
addto = input()
print("Addto", addto)
choice = input("Can he do stage?(y/n): ")
if choice == "y":
stage_list.append(addto)
choice = input("Can he do mic?(y/n): ")
if choice == "y":
mic_list.append(addto)
choice = input("Can he do sound?(y/n): ")
if choice == "y":
all_list.append(addto)
my_list.append(addto)
为什么你有一个for循环<代码>对于addto中的str:
input
是您正在调用的函数名,因此它永远不会等于“y”
(在计算input==“y”
)时),因此它永远不会被添加。而且input
的返回值也应该被分配给一个变量以供使用,不要使用input
作为变量名,比如flag=input(“他能做什么吗?(y/n):”)如果flag==“y”:
你调用input()
,它返回输入的字符串,但是你没有把它放在变量中,所以它会被丢弃。然后将输入
功能与“y”
进行比较。还有,为什么会有for循环?您不想多次询问用户。谢谢,只是吹毛求疵,键入(输入)=内置函数或方法