两段字典匹配Python列表推导式的性能差异分析问询
Hey there! Let's break down these two code snippets and their performance differences, building on our recent discussion:
First, let's confirm what both snippets do: they iterate over each string s in the list lst, check if any key from dictionary d exists within s, return the corresponding value if a match is found, and fall back to returning s itself if no match exists.
The First Snippet
res = [d.get(next((k for k in d if k in s), None), s) for s in lst]
Here's the play-by-play: for each s, we first use a generator to hunt down the first matching key k in d that lives inside s. Then we pass that key to d.get() to pull the associated value. If no key matches, d.get() uses s as the default fallback.
The Second Snippet
res = [next((v for k,v in d.items() if k in s), s) for s in lst]
This one cuts out the middleman: instead of finding the key first and then doing a separate lookup, we loop directly over d.items()—which gives us both the key k and its value v in a single pass. As soon as we spot a k that's in s, we return the paired v right away. No extra dictionary lookup required!
Why the Second Snippet is More Performant
You’re totally correct about the performance edge here. The first approach adds an unnecessary step: when a matching key is found, it does two distinct operations—locating the key via the generator, then fetching the value with d.get(). The second snippet eliminates that extra lookup by grabbing the value at the same time it checks the key.
For small dictionaries, this difference might feel trivial, but as d grows larger, that extra lookup (even though dictionary access is O(1) in theory, it still has overhead) adds up over repeated iterations through lst.
内容的提问来源于stack exchange,提问作者jferard

