简体   繁体   English

具有两个输出的列表理解

[英]List comprehension with two outputs

I am trying to optimize this code:我正在尝试优化此代码:

num = 10
for j in xrange(0,num):
  u[j],v[j] = rk4(du,dv,t,dt,u[j],v[j])

where u and v are input arrays and rk4() returns two values for two input values.其中 u 和 v 是输入数组,而 rk4() 为两个输入值返回两个值。 Using list comprehension I would do something like this:使用列表理解我会做这样的事情:

u,v=[rk4(du,dv,t,dt,u[j],v[j])) for j in range(0,num)]

The list comprehension works.列表理解有效。 But the output is in a different format.但是输出的格式不同。 Is it possible to optimize this kind of operation using list comprehension?是否可以使用列表理解来优化这种操作?

Edit: The desired output would be two arrays/lists of the form编辑:所需的输出将是表单的两个数组/列表

u,v = [u1,u2,u3,....],[v1,v2,v3,...]

What I get is the of the following form:我得到的是以下形式:

[(u1,v1),(u2,v2),(u3,v3),...]

It appears that you want to transform a sequence of pairs into two sequences.看来您想将一对序列转换为两个序列。 There is a standard idiom in Python to do this using the zip function and argument unpacking: Python 中有一个标准的习惯用法可以使用zip函数和参数解包来做到这一点:

>>> seq_of_pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> u, v = zip(*seq_of_pairs)
>>> u
('a', 'b', 'c', 'd')
>>> v
(1, 2, 3, 4)

So you can use a list comprehension (or generator expression) to produce the sequence of pairs using zip , and then use that trick to extract the two sequences:因此,您可以使用列表推导式(或生成器表达式)使用zip生成对序列,然后使用该技巧提取两个序列:

result = [ rk4(..., ui, vi) for ui, vi in zip(u, v) ]
u, v = zip(*result)

You can do u, v = map(list, zip(*result)) if you need them to be lists instead of tuples.如果你需要它们是列表而不是元组u, v = map(list, zip(*result))你可以做u, v = map(list, zip(*result))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM