我可以在一行中组合 2 个列表理解吗?

Can I combine 2 list comprehensions in a single line?

这是我的 Python 代码的一部分:

pstat1 = [plotvex(alpha,beta,j)[0] for j in range(5)]
ptset1 = [plotvex(alpha,beta,j)[1] for j in range(5)]

其中 plotvex 是 returns 2 项的函数。我想使用列表理解生成两个列表 pstat1ptset1,但我想知道有没有一种方法不需要调用该函数两次?谢谢:)

你说得很对,你不想为每组参数调用两次 plotvex() 函数。

所以,只调用一次,然后生成pstat1pstat2

pv = [plotvex(alpha,beta,j) for j in range(5)]
pstat1 = [item[0] for item in pv]
ptset1 = [item[1] for item in pv]

假设 plotvex() returns 正好是一个 2 元组*,这应该可行:

pstat1, ptset1 = zip(*[plotvex(alpha, beta, j) for j in range(5)])

zip(*iterable_of_iterables) 是 'rotate' 从垂直到水平的列表列表的常用习语。因此,[plotvex(alpha, beta, j) for j in range(5)] 将不再是 2 元组列表,而是两个单列列表,每半个元组各有一个列表。

*这里是参数解包操作符


*如果它 returns 多于一个 2 元组,那么只需执行 plotvex(alpha, beta, j)[:2] 而不是取前两个元素