[英]Dictionaries with tuples that have lists as values
How can i have a tuple that has a list as a value. 我怎么能有一个列表作为值的元组。
Fx if i want to have a structure like this. FX,如果我想拥有这样的结构。
( Somechar , Somelist[] ) (Somechar,Somelist [])
And how would i iterate through a dictionary of these things? 我将如何遍历这些东西的字典?
You can add a list to a tuple just like any other element. 您可以像其他任何元素一样向元组添加列表。 From a dictionary, you can access each element of the tuple by indexing it like so:
d[key][0]
and d[key][1]
. 从字典中,您可以通过对元组进行索引来访问它的每个元素,如下所示:
d[key][0]
和d[key][1]
。 Here is an example: 这是一个例子:
>>> d = {} >>> d["b"] = ('b', [2]) >>> d["a"] = ('a', [1]) >>> for k in d: ... print(d[k][0], d[k][1]) ... ('a', [1]) ('b', [2])
A tuple can contain anything you like. 元组可以包含任何您喜欢的东西。 It just works the same as a nested list.
它的工作原理与嵌套列表相同。
>>> myvar = ('d', [1, 2])
>>> myvar[0]
'd'
>>> myvar[1]
[1, 2]
>>> myvar[1][1]
2
Here's a simple example: 这是一个简单的例子:
>> a = ('a', ['a list'])
>> a
('a', ['a list'])
>> b = dict((a,))
{'a': ['a list']}
for i, j in b.iteritems():
print i, j
a ['a list']
Does that answer your question? 这是否回答你的问题? The dict constructor takes a list/tuple of (key, value) tuples.
dict构造函数采用(键,值)元组的列表/元组。 Also keep in mind the ',' character is constructor for a tuple (not just the () ).
还请记住,“,”字符是元组的构造函数(而不仅仅是())。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.