python-没有分配的列表理解 [英] python - list comprehension without assignment

查看:46
本文介绍了python-没有分配的列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我正在使用BeautifulSoup解析目录索引以及zip文件的路径列表,并且遇到了一件有趣的事情.假设我想获取我获得的标签的所有href属性,并将其直接放入队列:

Today I was parsing a directory index with a list of paths to zip files using BeautifulSoup and came across an interesting thing. Let's assume I would like to take all the href properties of the tags I got and put them directly into a Queue:

q = Queue.Queue()
[q.put(tag['href']) for tag in soup.findAll('a')]

我从来没有遇到过这样的情况,即在不将其分配给任何东西的情况下直接用于内联理解,只是通过一些常规调用生成另一个迭代器.这被认为是不好的做法吗?本身就是"pythonic"吗?有没有更好的一线产品来将所有物品放入队列?

I've never run into a situation like this before where a comprehension could be used inline without assigning it to anything, just to generated another iterator through some routine call. Is this considered bad practice? Is it "pythonic", per se? Was there a better one-liner to put all the items into the queue?

推荐答案

这个问题已经问了很多遍,例如,此处.但这是一个有趣的问题.列表推导用于其他目的.

This has been asked many times, e.g., here and here. But it's an interesting question, though. List comprehensions are meant to be used for something else.

其他选项包括

  1. 使用map()-与样本基本相同
  2. 使用filter()-如果您的函数返回None,您将获得一个空列表
  3. 只是一个普通的for-循环
  1. use map() - basically the same as your sample
  2. use filter() - if your function returns None, you will get an empty list
  3. Just a plain for-loop

,而普通循环则是更可取的方法.在这种情况下,它在语义上都是正确的,所有其他方式,包括列表理解,副作用的滥用概念.

while the plain loop is the preferable way to do it. It is semantically correct in this case, all other ways, including list comprehension, abuse concepts for their side-effect.

在Python 3.x中,map()filter()是生成器,因此在您迭代它们之前不执行任何操作.因此我们需要例如list(map(...)),这会使情况变得更糟.

In Python 3.x, map() and filter() are generators and thus do nothing until you iterate over them. So we'd need, e.g., a list(map(...)), which makes it even worse.

这篇关于python-没有分配的列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆