函数的python列表

2024-04-26 00:05:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了一个问题,我在一个函数中创建了两个列表,但是我不能在函数外使用它们,因为它说“NameError:name”ListB“未定义”。你知道吗

我需要这个列表来创建一个元组,并将元组写入一个命令行:)

#
#create 2 lists and 1 dictonary with the same length
#Example: index length is 3
def adder():

    ListB = list()
    ListC = list()

    while True:

        insert1 = input("List2 add: ")
        insert2 = input("List3 add: ")

        ListB.append(insert1)
        ListC.append(insert2)

        print("""if list length is ok, write "ok" """)
        inputPerson = str(input())

        if inputPerson == "ok":
            break

    return ListB, ListC

#run adder
adder = adder()

list2 = [] # create list2/3 with same index length 
list3 = [] # to add ListB to list2 and ListC to list3

list2.append(ListB) #add ListB to list2
list3.append(ListC) #add ListC to list3


tupleList = list(zip(list2, list3)) # take element from list2 and
print(tupleList)  #Test             # list3 in (x, y) order

#create a dictonary with they keyword KeyX X = 0,1,2,3...n : tupleList[0]..[n]
#depending on index length, but X = tupleList[n]!!
dict_List = { \
    'Key0' : tupleList[0],
    'Key1' : tupleList[1],
    'Key2' : tupleList[2],
    }

#print out the result
print("Dict_List:", dict_List)
print("Key0", dict_List['Key0'])
print("Key1", dict_List['Key1'])
print("Key2", dict_List['Key2'])

现在我不知道如何创建一个口述,将自动 用KeyX等创建一个新的“条目”

我希望有人能帮助我。你知道吗


Tags: toaddcreatelengthdictlistprintappend
1条回答
网友
1楼 · 发布于 2024-04-26 00:05:01

尝试以下操作:

ListB, ListC = adder()

当函数返回两个值时,可以将它们像元组一样解压。你知道吗

您必须知道的是,从函数中声明变量会使其成为局部变量,并限制在函数的作用域内。因此,您不能从外部访问它。你知道吗

当您调用adder()时,返回的值没有任何名称,它只是一个值,您必须将它赋给一个新变量,就像您所做的那样:adder = adder()。这意味着变量adder现在包含两个返回的列表。你知道吗

但是,您正在覆盖您的函数(因为名称相同),这被认为是不好的做法。你最好做些类似lists = adder()的事情。你知道吗

然后,可以使用lists[0]访问创建的ListB。但正如我所说,您也可以直接解包:ListB, ListC = adder()。你知道吗

相关问题 更多 >