【问题标题】:How do I retrieve more than one item pair from a dictionary如何从字典中检索多个项目对
【发布时间】:2014-04-23 07:40:45
【问题描述】:

有谁知道我如何从字典中检索两对 我正在尝试以更紧凑的格式呈现数据

a = {1:'item 1', 2:'item 2', 3:'item 3', 4:'item 4' }
for i,j,k,l in a:
    print i, ' - ' ,j , ' , ' ,k, ' - ' ,l

1 - 项目 1 , 2 - 项目 2

3 - 项目 3 , 4 - 项目 4

编辑 - 抱歉让它看起来像上面

【问题讨论】:

标签: python for-loop dictionary


【解决方案1】:

您可以使用iter() 将已排序的项目转换为迭代器,然后遍历该迭代器以获取对。

>>> from itertools import chain
>>> items =  iter(sorted(a.items())) #As dicts are unordered
>>> print ' '.join('{} - {} , {} - {}'.format(*chain(x, next(items))) for x in items)
1 - item 1 , 2 - item 2 3 - item 3 , 4 - item 4

获取对的另一种方法是使用zip(*[iter(seq)]*n) 技巧:

>>> items = sorted(a.items())
>>> grouped = zip(*[iter(items)]*2)
>>> print ' '.join('{} - {} , {} - {}'.format(*chain(*x)) for x in grouped)
1 - item 1 , 2 - item 2 3 - item 3 , 4 - item 4

【讨论】:

  • 再次道歉! - 我没有按照我真正想要的方式表示输出。你的方法完美地产生了我最初要求的东西。干杯
  • @FloggedHorse 这应该可以:for x in grouped: print '{} - {} , {} - {}'.format(*chain(*x))
【解决方案2】:

这是你想要的吗:

a = {1:'item 1', 2:'item 2', 3:'item 3', 4:'item 4' }

for i,j in a.items():
    print i, ' - ' ,j, ',',

[OUTPUT]
1 - item 1 , 2 - item 2 , 3 - item 3 , 4 - item 4 ,

或者更简单的

l = [' - '.join(map(str, i)) for i in a.items()]

>>> print l
1 - item 1, 2 - item 2, 3 - item 3, 4 - item 4

【讨论】:

  • @Aशwiniचhaudhary,能否解释一下我的错误?谢谢
  • 将此1 - item 1 , 2 - item 2 3 - item 3 , 4 - item 4 与您的输出进行比较。
  • @Aशwiniचhaudhary,你的意思是我在 2 到 3 之间的额外 , 吗?
  • 对不起我的错误!它完成了我的要求,但我要求错了:( - 我已将输出编辑为我想要的方式。您的示例完全依赖于 print 语句末尾的逗号。- 干杯
猜你喜欢
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
  • 2017-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多