简体   繁体   中英

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. 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. 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

[('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).

for name in (''.join(t) for t in  product(['a', 'b'], ['', 'Bar'])):

For this question, moreIter(KEYS) return the keys of src. So:

>>> d = {k:src[k] for k in src.keys()}
>>> d
{'a': 1, 'aBar': 2, 'b': 3, 'bBar': 4}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM