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

转载:https://blog.csdn.net/weixin_42427638/article/details/85261284

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

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
 

猜你喜欢

转载自blog.csdn.net/qq_38409301/article/details/89761307
今日推荐