[英]python List from function
我遇到了一個問題,我正在一個函數中創建2個列表,但由於該函數顯示“ NameError:未定義名稱“ 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等自動創建新的“條目”。
我希望有人能幫助我。
嘗試類似:
ListB, ListC = adder()
當函數返回兩個值時,您可以像元組一樣對它們進行解壓縮。
您需要知道的是,從函數內部聲明變量會使它成為局部變量,並限於函數的作用域。 因此,您不能從外部訪問它。
調用adder()
,返回的值沒有任何名稱,它只是一個值,您必須像以前一樣將其分配給新變量: adder = adder()
。 這意味着變量adder
現在包含兩個返回的列表。
但是,您正在重寫函數(因為名稱相同),這被認為是不好的做法。 您最好做一些類似lists = adder()
事情。
然后,您可以使用lists[0]
訪問創建的ListB
。 但是正如我所說,您也可以直接解壓縮它: ListB, ListC = adder()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.