开发者

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). 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
101开发者_StackOverflow中文版1
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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜