[英]Why a list of tuples can be converted to dict where as tuple of tuples can't be
please try to execute this you should understand my question请尝试执行此操作,您应该了解我的问题
a=[(x,1)]
b=((x,1))
c=((x,1),)
dict(a) #runs successfully
dict(b) # gives error
dict(c) #runs successfully
I want to understand why a and c are valid but b is not??我想了解为什么 a 和 c 有效但 b 无效?
Variables "a" and "c" have the same structure, with an iterable holding a key-value pair {x: 1}, whereas variable "b" has the assignment statement of just ((x,1)), so python executes that as an equivalent to (x,1) because an tuple assignment statement with only one element needs to have the ending comma to signify that it is a "tuple", otherwise it is just parenthesis.变量“a”和“c”具有相同的结构,其中一个可迭代对象包含一个键值对 {x: 1},而变量“b”的赋值语句只是 ((x,1)),因此 python 执行这与 (x,1) 等效,因为只有一个元素的元组赋值语句需要以逗号结尾来表示它是一个“元组”,否则它只是括号。 Python doesn't really understand this structure as a "key-value" pair. Python 并不真正将这种结构理解为“键值”对。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.