Python - 将列表字典扁平化为唯一值?

新手上路,请多包涵

我在 python 中有一个列表字典:

 content = {88962: [80, 130], 87484: [64], 53662: [58,80]}

我想把它变成唯一值的列表

[58,64,80,130]

我写了一个手动解决方案,但它是一个手动解决方案。我知道有更简洁、更优雅的方法可以通过列表推导、map/reduce、itertools 等来做到这一点。有人知道吗?

 content = {88962: [80, 130], 87484: [64], 53662: [58,80]}
result = set({})
for k in content.keys() :
    for i in content[k]:
        result.add(i)
# and list/sort/print just to compare the output
r2 = list( result )
r2.sort()
print r2

原文由 Jonathan Vanasco 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 468
2 个回答

集理解

蟒蛇 3:

 sorted({x for v in content.values() for x in v})

蟒蛇2:

 sorted({x for v in content.itervalues() for x in v})

原文由 nneonneo 发布,翻译遵循 CC BY-SA 4.0 许可协议

在 python3.7 中,您可以组合使用 .valueschain

 from itertools import chain
sorted(set(chain(*content.values())))
# [58, 64, 80, 130]

# another option is `itertools.groupby`
from itertools import groupby
[k for k, g in groupby(sorted(chain(*content.values())))]

在python2.7

 from itertools import chain
sorted(set(chain.from_iterable(content.itervalues())))
# [58, 64, 80, 130]

# another option is `itertools.groupby`
[k for k, g in groupby(sorted(chain.from_iterable(content.itervalues())))]

原文由 Jon Clements 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题