[英]Is there a Pythonic way to iterate over an “expanded” source list?
I created a generator expression that builds a dictionary out of more than the source keys, like so: 我创建了一个生成器表达式,它构建了一个超过源键的字典,如下所示:
def moreIter(names):
for name in names:
yield name
yield name + "Bar"
KEYS = ("a", "b")
src = {"a": 1, "aBar": 2, "b": 3, "bBar": 4, "c": 0, "cBar": 1, "d": 10}
d = {key: src[key] for key in moreIter(KEYS)}
I was wondering if there is a more "pythonic" way to do something like this. 我想知道是否有更“pythonic”的方法来做这样的事情。 It seems all the standard library functions I've come across that iterate through a list will return something of an equal or smaller length than the original list, but in this case I want to iterate through an expanded result.
似乎我遇到的所有标准库函数迭代遍历列表将返回与原始列表相等或更小的长度,但在这种情况下,我想迭代扩展的结果。
You could use a multi-level generator: 您可以使用多级生成器:
src = {"a": 1, "aBar": 2, "b": 3, "bBar": 4}
d = {key: src[key] for item in 'ab' for key in (item, item+'Bar')}
You could use itertools.product in this case. 在这种情况下,您可以使用itertools.product 。 It really depends on how complex your additive keys will be:
这实际上取决于您的附加键的复杂程度:
from itertools import product
for name in map(''.join, product(['a', 'b'], ['', 'Bar'])):
yield name
# ['a', 'aBar', 'b', 'bBar']
product
generates a list of tuples product
生成元组列表
[('a', ''), ('a', 'Bar'), ('b', ''), ('b', 'Bar')]
Then map
uses the ''.join
function to combine each tuple into a single string (you could use a list comprehension here instead of map
but I think it makes it less readable because it's already in a for
loop). 然后
map
使用''.join
函数将每个元组组合成一个字符串(你可以在这里使用列表推导而不是map
但我认为它使它更不易读,因为它已经在for
循环中)。
for name in (''.join(t) for t in product(['a', 'b'], ['', 'Bar'])):
For this question, moreIter(KEYS) return the keys of src. 对于这个问题,moreIter(KEYS)返回src的键。 So:
所以:
>>> d = {k:src[k] for k in src.keys()}
>>> d
{'a': 1, 'aBar': 2, 'b': 3, 'bBar': 4}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.