Python:更清晰的列表理解
有没有更简洁的方法来编写此内容:
for w in [w for w in words if w != '']:
我想循环字典 words
,但仅限 != ''
的单词。谢谢!
Is there a cleaner way to write this:
for w in [w for w in words if w != '']:
I want to loop over a dictionary words
, but only words that != ''
. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您在这里不需要列表。只需写:
You don't need a listcomp here. Just write:
假设您正在寻找钥匙,为什么不尝试:
Assuming that you are after the keys, why not try:
测试元素不等于
''
不会过滤掉空白元素。如果这就是您所追求的,您可能需要使用str.isspace
(或正则表达式)。如果您使用列表理解,您将创建列表的额外副本作为中间对象。可能没什么大不了的,但生成器不会使用额外的内存。
我会用生成器这样做:
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 usestr.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:
我认为你的解决方案不是最优的。您将迭代列表
words
两次 - 一次在列表理解中创建非空术语,再次在循环中进行处理。如果你使用像这样的 genexp 会更好。这样, genexp 将延迟返回非空列表。
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.That way, the genexp will lazily return a list of non-nulls.
filter(lambda w: w != '', Words)
或filter(None, Words)
这是建议,它可能不是解决您问题的最佳解决方案。
filter(lambda w: w != '', words)
orfilter(None, words)
this is suggestion, it may not be the best solution for your problem.
外层 for 循环体的作用是什么?
如果它是一个函数调用,您可能只需执行以下操作:
[f(w) for w in Words if w != '']
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 != '']