【问题标题】:Generating tuples from dictionary key and it's values从字典键及其值生成元组
【发布时间】:2020-11-05 22:54:18
【问题描述】:

我有一个字典列表,每个键映射到列表

[    {28723408: [28723409]},
     {28723409: [28723410]},
     {28723410: [28723411, 28723422]},
     {28723411: [28723412]},
     {28723412: [28723413]},
     {28723413: [28723414, 28, 28723419]}]

我想创建映射到每个列表值的元组键列表:

[(28723408, 28723409),
 (28723409, 28723410),
 (28723410, 28723411),
 (28723410, 28723422),
 (28723411, 28723412),
 (28723412, 28723413),
 (28723413, 28723414),
 (28723413, 28),
 (28723413, 28723419),]

我是按照以下方式完成的:

for pairs in self.my_pairs:
    for source, targets in pairs.items():
        for target in targets:
            pair_list.append((source, target))

有更多的 Pythonic 方式吗?

【问题讨论】:

  • 我尝试过的所有花哨的 oneliners 的可读性都比你做的要差。
  • 您的字典列表中的键是否已知不同,否则会发生什么?
  • @guidot,他们没有区别。我只需要制作不需要过滤器的映射。
  • 每个字典是否只有一个键?
  • @RiccardoBucco,请不要做这个假设。

标签: python dictionary


【解决方案1】:

我会做你已经做过的事情,但是使用列表理解。

pair_list = [(source, target)
             for pairs in self.my_pairs
             for source, targets in pairs.items()
             for target in targets]

这种方法可能看起来与您的方法相同,但要快得多!检查例如this 问题(或this)。这个事实也得到了证实here

如果您想要更“pythonic”的方法,您也可以使用itertools.productitertools.chain

from itertools import chain, product

pair_list = list(chain(*(product((source,), targets)
                         for pairs in self.my_pairs
                         for source, targets in pairs.items())))

【讨论】:

  • 我正要使用列表理解发布类似的答案。非常好!
猜你喜欢
  • 2015-07-07
  • 1970-01-01
  • 1970-01-01
  • 2021-07-21
  • 1970-01-01
  • 2018-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多