尝试解读Python列表推导式

2024-03-29 08:52:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经有几年没有在Python中工作了,我正在尝试弄清楚一个特定的列表理解意味着什么。你知道吗

代码如下:

cols = [i for i, col in enumerate(desc) if col[0].startswith('word')]

我正在查看Python文档中的列表理解页面,没有看到任何东西能够描述逗号和单独语句的含义。你知道吗

这段代码如何看待非列表理解?你知道吗


Tags: 代码in文档列表forifcol页面
3条回答
cols = [i for i, col in enumerate(desc) if col[0].startswith('word')]

是“的缩写”

cols = []
for i, col in enumerate(desc)
    if col[0].startswith('word'):
        cols.append(i)

所以你不应该把逗号看作是语句的分隔,而是值的分隔(例如life, universe, everything = the_answerli = [4, 2]

How would this code look at a non-list comprehension?

cols = []
for i, col in enumerate(desc):
    if col[0].startswith('word'):
        cols.append(i)

它只取决于循环的iteable中的值的数量是的。所以呢for关键字后面可以跟任意变量名。你知道吗

在本例中,由于enumerate()包含iterable的项,它使用了2个变量i, col。你知道吗

有关iterable解包的更多信息,请阅读pep3131https://www.python.org/dev/peps/pep-3132/

A tuple (or list) on the left side of a simple assignment (unpacking is not defined for augmented assignment) may contain at most one expression prepended with a single asterisk (which is henceforth called a "starred" expression, while the other expressions in the list are called "mandatory"). This designates a subexpression that will be assigned a list of all items from the iterable being unpacked that are not assigned to any of the mandatory expressions, or an empty list if there are no such items.

相关问题 更多 >