[英]Printing out values of a dictionary line by line in Python
I have the following code here: 我在这里有以下代码:
tel = {2: [[0, 0, 1, 1], [0, 1, 0, 1]], 3: [[1, 0, 1, 1], [1, 0, 1, 1], [1, 0, 0, 0], [1, 0, 1, 1], [1, 0, 1, 1]]}
for i in tel.values():
a = ''.join(map(str,i))
print a
The dictionary tel
consists of keys which are the number of 1s in the keys value(here, they are lists of binary). 字典
tel
由键组成,这些键是键值中1的数目(这里是二进制列表)。 The key's value/s can have more than one (in this case they are) 键的值可以具有多个(在这种情况下,它们是一个或多个)
What this does is print the values that belong to each key line by line. 这就是逐行打印属于每个键的值。
My goal: 我的目标:
I want to print the string version of each value. 我想打印每个值的字符串版本。
In the example above, I want the output to be: 在上面的示例中,我希望输出为:
0011
0101
1011
1011
1000
1011
1011
How would I accomplish this? 我将如何完成?
>>> for x in tel.values():
... for y in x:
... print ''.join(str(z) for z in y)
...
0011
0101
1011
1011
1000
1011
1011
You could do: 您可以这样做:
for key in tel:
for num in tel[key]:
print ''.join(str(n) for n in num)
For your example this prints: 对于您的示例,将打印:
0011
0101
1011
1011
1000
1011
1011
Create a generator expression to traverse the data structure, and then just print its content. 创建一个生成器表达式以遍历数据结构,然后仅打印其内容。
val_gen = (''.join(map(str,v)) for vs in tel.values() for v in vs)
for v in val_gen: # Or sorted(val_gen) if order matters.
print v
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.