-2

我正在尝试一一阅读字典中的所有元素。我的字典如下“测试”所示。

test ={'line4': (4, 2), 'line3': (3, 2), 'line2': (2, 2), 'line1': (1, 2), 'line10': (10, 2)}

我想按照下面的示例代码进行操作。

for i in range(1,len(test)+1):
    print test(1) # should print all the values one by one

谢谢你

4

4 回答 4

3
#Given a dictionary
>>> test ={'line4': (4, 2), 'line3': (3, 2), 'line2': (2, 2), 'line1': (1, 2), 'line10': (10, 2)}

#And if you want a list of tuples, what you need actually is the values of the dictionary
>>> test.values()
[(4, 2), (3, 2), (2, 2), (1, 2), (10, 2)]

#Instead if you want a flat list of values, you can flatten using chain/chain.from_iterable
>>> list(chain(*test.values()))
[4, 2, 3, 2, 2, 2, 1, 2, 10, 2]
#And to print the list 
>>> for v in chain.from_iterable(test.values()):
    print v


4
2
3
2
2
2
1
2
10
2

分析你的代码

for i in range(1,len(test)+1):
    print test(1) # should print all the values one by one
  1. 你不能索引字典。字典不是像列表那样的序列
  2. 您不使用括号来索引。它变成了一个函数调用
  3. 要迭代字典,您可以迭代键或值。
    1. for key in test按键迭代字典
    2. for key in test.values()按值迭代字典
于 2013-03-28T05:15:29.943 回答
3

这里有几种可能性。你的问题很模糊,你的代码甚至还没有接近工作,所以很难理解这个问题

>>> test ={'line4': (4, 2), 'line3': (3, 2), 'line2': (2, 2), 'line1': (1, 2), 'line10': (10, 2)}
>>> for i in test.items():
...     print i
... 
('line4', (4, 2))
('line3', (3, 2))
('line2', (2, 2))
('line1', (1, 2))
('line10', (10, 2))
>>> for i in test:
...     print i
... 
line4
line3
line2
line1
line10
>>> for i in test.values():
...     print i
... 
(4, 2)
(3, 2)
(2, 2)
(1, 2)
(10, 2)
>>> for i in test.values():
...     for j in i:
...         print j
... 
4
2
3
2
2
2
1
2
10
2
于 2013-03-28T05:32:15.077 回答
2

试试这个:

for v in test.values():
    for val in v:
        print val

如果您需要一份清单:

print [val for v in test.values() for val in v ]

如果要从 dict 打印每条记录:

for k, v in test.iteritems():
    print k, v
于 2013-03-28T05:14:57.140 回答
1

您可以使用嵌套理解:

>>> test ={'line4': (4, 2), 'line3': (3, 2), 'line2': (2, 2), 'line1': (1, 2), 'line10': (10, 2)}
>>> print '\n'.join(str(e) for t in test.values() for e in t)
4
2
3
2
2
2
1
2
10
2

由于字典在 Python 中是未排序的,因此您的元组也将是未排序的。

于 2013-03-28T05:20:23.103 回答