欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python中,(x for y in z for x in y)这个结构怎么理解?

程序员文章站 2023-12-23 11:23:46
...

看代码时偶然看到的一个写法:

sentences=[y for x in sentences for y in x]

之前没看到过,一头雾水,经过查资料后发现是这样去理解的:

def f(z):
    for y in z:
        for x in y:
           yield x

英文描述:[item for sublist in list for item in sublist]

也就是:子列表中项目的子列表项目

 效果展示:

> # flatten a list using a listcomp with two 'for'
> vec = [[1,2,3], [4,5,6], [7,8,9]]
> [num for elem in vec for num in elem]

[1, 2, 3, 4, 5, 6, 7, 8, 9]

作用:将列表展平

当然还有更高级的用法:

 [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

 它等价于:

>>> combs = []
>>> for x in [1,2,3]:
...     for y in [3,1,4]:
...         if x != y:
...             combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

最后附上python3官方文档连接:https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

上一篇:

下一篇: