我有几行来填充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
第一个,这很烦人。里面有很多x
,y
而且大部分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]}
原始代码是“最pythonic”还是单行代码之一更好?还有什么?