简体   繁体   English

为什么元组列表可以转换为字典,而元组的元组不能

[英]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.

相关问题 要列出或听写的元组的元组 - Tuple of tuples to list or dict 元组的元组只有一个元组时,无法解包元组。 为什么? 与元组数组一起使用 - Can't unpack tuples when tuple of tuples has single tuple. Why? Works with array of tuples 我如何从 dict 值和元组列表中获取每个元素并从中生成一个元组 - How i can get every element from dict value and list of tuples and make one tuple from it 如何遍历元组列表,在其中将一个列表中的元组与同一列表中的其他元组进行比较? - How can you loop over lists of tuples where you compare the tuple in one list to the other tuples in the same list? 使用列表合并元组中的元组并转换为dict - Merging tuples in a tuple with list and converting to dict 为什么 [:][:1] 不适用于元组列表? 如何在列表中的所有元组中获得某个索引的迭代? - Why [:][:1] don't work for list of tuples? How can I get iterable for a some index in all tuples in list? 如何将元组列表写入到csv文件中,其中元组的第一个元素是字典? - How can I write a list of tuples to a csv file where the first element of the tuple is a dictionary? Python:元组列表:比较所有元组并检索其中元组的元素不等于任何其他元组的元组 - Python: List of tuples: compare all tuples and retrive tuples where the elements of tuples are not equal to any other tuple 列表的字典变成元组的元组的字典 - Dict of list of list into dict of tuples of tuples 如何获得元组和元组列表之间的最近距离? - How can i get the closest distance between a tuple and a list of tuples?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM