首页 > 解决方案 > 在 for 中找到 Python .append 时不起作用,否则

问题描述

使用列表创建者为声音工作人员生成任务。根据他们接受的培训和他们能够从事的工作,创建 4 个列表并将人员添加到各种列表中。我有一份包含所有人员的基本清单。.append 适用于该列表,但对于所有带有条件的列表,名称都不会附加。

我尝试将我的 for from for str 添加到其他东西,但到目前为止没有任何效果。

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

标签: pythonstringlistinputappend

解决方案


您需要使inputs 单行:

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)

你的代码没有工作,因为你input,但是你失去了对象,因为你没有分配变量,也没有在任何地方使用它,OTOHinput是一个关键字,它是<built-in function input>,所以它绝对不是"y"


推荐阅读