Python: cleaner list comprehension
Is there a cleaner way to write this:
fo开发者_开发知识库r w in [w for w in words if w != '']:
I want to loop over a dictionary words
, but only words that != ''
. Thanks!
You don't need a listcomp here. Just write:
for w in words:
if w != '':
# ...
Assuming that you are after the keys, why not try:
[w for w in words if w]
Testing that an element does not equal ''
isn't going to filter out whitespace elements. If that's what you're after, you probably want to use str.isspace
(or a regular expression).
If you use a list comprehension, you'll make an extra copy of the list as an intermediary object. Probably not a big deal, but a generator won't use the extra memory.
I'd do it like this, with a generator:
for word in (w for w in words if not w.isspace()):
# do stuff
I think your solution is sub optimal. You're iterating over the list words
twice - once in the list comprehension to create the non-null terms and again in the loop to do the processing. It would be better if you used a genexp like so.
for w in (x for x in words if x): process(w)
That way, the genexp will lazily return a list of non-nulls.
filter(lambda w: w != '', words)
or filter(None, words)
this is suggestion, it may not be the best solution for your problem.
What does the body of the outer for loop do?
If it's a function call you could potentially just do:
[f(w) for w in words if w != '']
精彩评论