【问题标题】:How to create a list of tuples from the values of a dictionary of lists? [duplicate]如何从列表字典的值创建元组列表? [复制]
【发布时间】:2019-01-19 10:15:19
【问题描述】:

字典my_entities 看起来像这样:

{'Alec': [(1508, 1512),
          (2882, 2886),
          (3011, 3015),
          (3192, 3196),
          (3564, 3568),
          (6453, 6457)],
 'Downworlders': [(55, 67)],
 'Izzy': [(1499, 1503), (1823, 1827), (7455, 7459)],
 'Jace': [(1493, 1497),
          (1566, 1570),
          (3937, 3941),
          (5246, 5250)]...}

我希望能够将所有键的值保存在一个元组列表中,以便与其他列表进行一些比较。

到目前为止,我已经尝试过这段代码:

from pprint import pprint    
list_from_dict = []
for keys in my_entities:
    list_from_dict = [].append(my_entities.values())
pprint(list_from_dict)

它输出None

我想要的输出如下所示:

[         (1508, 1512),
          (2882, 2886),
          (3011, 3015),
          (3192, 3196),
          (3564, 3568),
          (6453, 6457),
          (55, 67), (1499, 1503), (1823, 1827), (7455, 7459),...]

如何调整代码来做到这一点?

提前致谢!

编辑

我没有找到其他已回答的问题,因为它没有关键字 dictionary。如果它确实被视为重复,那么它可以被删除 - 我有我的答案。谢谢!

【问题讨论】:

  • 这是对my_entities.values() 的简单展平操作。所以 [t for v in my_entities.values() for t in v]` 或 itertools.chain.from_iterable(my_entities.values()) 如果你只需要一个迭代器。

标签: python list dictionary tuples


【解决方案1】:

使用来自itertools 模块的chainchain.from_iterable

from itertools import chain

d = {'Alec': [(1508, 1512),
          (2882, 2886),
          (3011, 3015),
          (3192, 3196),
          (3564, 3568),
          (6453, 6457)],
 'Downworlders': [(55, 67)],
 'Izzy': [(1499, 1503), (1823, 1827), (7455, 7459)],
 'Jace': [(1493, 1497),
          (1566, 1570),
          (3937, 3941),
          (5246, 5250)]}

print(list(chain(*d.values())))

# [(1508, 1512), (2882, 2886), (3011, 3015), (3192, 3196), (3564, 3568),
#  (6453, 6457), (55, 67), (1499, 1503), (1823, 1827), (7455, 7459),
#  (1493, 1497), (1566, 1570), (3937, 3941), (5246, 5250)]

或者:

print(list(chain.from_iterable(d.values())))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 2011-08-29
    • 1970-01-01
    • 2018-12-15
    • 2018-01-14
    • 2021-11-22
    • 2014-12-18
    相关资源
    最近更新 更多