排列一个列表(或数组?)Python中的数字

2024-05-01 22:09:06 发布

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

我来自一个MATLAB背景,根据其他栈中的答案,到目前为止,这个简单的操作在Python中实现起来似乎非常复杂。通常,大多数答案使用for循环。

到目前为止我看到的最好的是

import numpy
start_list = [5, 3, 1, 2, 4]
b = list(numpy.array(start_list)**2)

有更简单的方法吗?


Tags: 方法答案importnumpyforarraystartlist
3条回答

最具可读性的可能是列表理解:

start_list = [5, 3, 1, 2, 4]
b = [x**2 for x in start_list]

如果你是函数类型,你会喜欢map

b = map(lambda x: x**2, start_list)  # wrap with list() in Python3

使用列表理解:

start_list = [5, 3, 1, 2, 4]
squares = [x*x for x in start_list]

注意:作为次要优化,执行x*xx**2(或pow(x, 2)))更快。

你可以使用列表理解:

[i**2 for i in start_list]

或者如果您使用的是numpy,则可以使用^{}方法:

In [180]: (np.array(start_list)**2).tolist()
Out[180]: [25, 9, 1, 4, 16]

^{}

In [181]: np.power(start_list, 2)
Out[181]: array([25,  9,  1,  4, 16], dtype=int32)

相关问题 更多 >