我有几行代码来填充set
。你知道吗
x = {1: {2: 4, 3: 6}, 5: {2:6, 10: 25, 14: 12}}
keys = set()
for y in x:
for z in x[y]:
keys.add(z)
# keys is now `set([2, 3, 10, 14])`
我无法摆脱这种感觉,我可以做得更好,但我提出的似乎没有什么是伟大的。大多数实现首先构建list
,这很烦人。在y
中有大量的x
,并且大多数y
具有相同的z
。你知道吗
# Builds a huuuuge list for large dicts.
# Adapted from https://stackoverflow.com/a/953097/241211
keys = set(itertools.chain(*x.values()))
# Still builds that big list, and hard to read as well.
# I wrote this one on my own, but it's pretty terrible.
keys = set(sum([x[y].keys() for y in x], []))
# Is this what I want?
# Finally got the terms in order from https://stackoverflow.com/a/952952/241211
keys = {z for y in x for z in x[y]}
原始代码是“最具python风格”还是其中一个行程序更好?还有别的吗?你知道吗
我将使用
itertools
模块,特别是chain
类。你知道吗您可以使用
dict.items()
:输出:
我会用
itervalues()
(在python3中只是values()
)不构建列表,并且这个解决方案不涉及字典查找(与{z for y in x for z in x[y]}
相反)。你知道吗相关问题 更多 >
编程相关推荐