我正在使用的API可以返回空的[]
列表。如何檢查Python中的列表是否爲空?
以下條件語句不按預期工作:
if myList is not None: #not working
pass
if myList is not []: #not working
pass
什麼工作?
我正在使用的API可以返回空的[]
列表。如何檢查Python中的列表是否爲空?
以下條件語句不按預期工作:
if myList is not None: #not working
pass
if myList is not []: #not working
pass
什麼工作?
if not myList:
print "Nothing here"
空列表評估爲False布爾環境(如if some_list:
)。
我喜歡Zarembisty的回答。儘管如此,如果你想更明確的,你總是可以做:
if len(my_list) == 0:
print "my_list is empty"
你可以這樣做,但它會違反pep 8,它說: - 對於序列(字符串,列表,元組),使用空序列爲空的事實。 是:如果不是序列: 如果序列: 編號:如果len(SEQ) 如果不是LEN(SEQ) – 2009-11-12 22:16:14
感謝您指出這一點對我來說,克里斯Lacasse。我不知道pep8,早些時候 – inspectorG4dget 2009-11-14 00:53:01
這也是一個普遍的表現悲觀:不要花時間計算潛在的長集合的元素,如果你只需要知道它是否是空的。 – 2015-08-12 12:38:01
使用'='而不是'被not'將做這項工作,雖然如果myList'形式是優選的'! – 2010-05-05 03:13:36