[英]update dict using nested for loop
我在下面有雙循環。 在第一個for循環中,我迭代遍歷tstLst1中的元素,然后對於每個元素,我將遍歷tstLst2中的元素,測試每個元素以查看它是否大於5,然后將tstLst2中的元素添加到新列表中tstEmpt1。 然后,我將tstLst1中每個元素的tstLst2值列表更新為dict作為鍵。 我在下面收到“Nonetype”錯誤,我不知道為什么。 有人可以指出問題並提出解決方案嗎?
碼:
tstLst1=[1,2,3]
tstLst2=[2,5,6]
tstDict1={}
for j in tstLst1:
tstEmpt1=[]
for i in tstLst2:
if i >5:
tstEmpt1=tstEmpt1.append(i)
tstDict1=tstDict1.update({j:tstEmpt1})
錯誤:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-19-89e025227797> in <module>
16 tstEmpt1=tstEmpt1.append(i)
17
---> 18 tstDict1=tstDict1.update({j:tstEmpt1})
19
AttributeError: 'NoneType' object has no attribute 'update'
您的問題是list.append()
返回None
因此當您執行tstEmpt1=tstEmpt1.append(i)
您將附加元素並將None
分配給列表。 下一次迭代拋出,因為None
沒有屬性'update'作為錯誤狀態。
與dictionary.update()
相同的情況。
刪除作業應該為您解決問題:
for j in tstLst1:
tstEmpt1=[]
for i in tstLst2:
if i >5:
tstEmpt1.append(i)
tstDict1.update({j:tstEmpt1})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.