【发布时间】:2020-05-07 13:07:13
【问题描述】:
想象一个理论上的 sn-p:
# just for this example: `bad_structure` contains a list of dicts with different keys
# for the same semantic
bad_structure = [{'path': '/dir/one'}, {'subdir': '/dir/two'}]
# i want to turn this into
# { '/dir/one': some_func('/dir/one'),
# '/dir/two': some_func('/dir/two')}
result = {}
for e in bad_structure:
# calculate a value which we will need more than once (here the key)
p = next(k for k in ('path', 'subdir') if k in e)
result[p] = some_func(p)
我现在想把它变成一个dict理解,我的第一个方法是这样的:
bad_structure = [{'path': '/dir/one'}, {'path': '/dir/two'}]
result = {next(k for k in ('path', 'subdir') if k in e):
some_func(next(k for k in ('path', 'subdir') if k in e))
for e in bad_structure}
其中包含两次丑陋、容易出错且速度慢的“计算”。我想将其重写为 s.th。喜欢
result = {p: some_func(p)
for p = next(k for k in ('path', 'subdir') if k in e)
for e in bad_structure}
这当然不是有效的 Python 代码..
在 Python 中这样的事情可能吗?
澄清一下:我不关心理解语法,而是重用没有单独变量声明的计算(这在封闭表达式中是不可能的)
【问题讨论】:
-
请注意,您的
p表达式可以重写为next(iter(e))。
标签: python python-3.x dictionary-comprehension