gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:20:25 34 4
gpt4 key购买 nike

我在 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

最佳答案

set comprehension :

Python 3:

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

Python 2:

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

关于Python - 将列表的字典扁平化为唯一值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13016129/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com