[英]Why do nested tuples evaluate to a single tuple but nested lists dont evaluate to a single list
在python中,如果我有:
((()))
或者我有
()
然后((())) == ()
和
if (()):
# is false
而
if [[]]:
# is true
元組與列表相比有何特殊之處?
他們沒有。
表達式(())
不是嵌套元組,它是一個用圓括號括起來的單個元組。 如果要創建僅包含x
的元組,則語法不是(x)
而是(x,)
。 因此嵌套的元組看起來像(((),),)
。
In [1]: (((),),) == () Out[1]: False In [2]: "x" == ("x") Out[2]: True In [3]: "x" == ("x",) Out[3]: False
從文檔 :
元組由逗號運算符構造(不在方括號內),帶或不帶括號,但空的元組必須帶括號,例如a,b,c或()。 單個項目元組必須帶有尾隨逗號,例如(d,)。
括號在python的許多其他地方使用,例如,將表達式分組(例如(x + y) * z
)。 另一方面,方括號構成一個列表。 簡而言之:
() == tuple()
(()) == (tuple()) == tuple() # outer parens unnecessarily groups the empty tuple
((),) == (), == tuple(tuple()) # the comma creates a single element tuple containing the empty tuple
[] == list()
[[]] == [[],] == list(list) # the comma here is optional since the constructor is the square brackets
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.