gpt4 book ai didi

python - 如何将列表中的每个元素乘以一个数字?

转载 作者:IT老高 更新时间:2023-10-28 20:31:25 25 4
gpt4 key购买 nike

我有一个 list :

my_list = [1, 2, 3, 4, 5]

如何将 my_list 中的每个元素乘以 5?输出应该是:

[5, 10, 15, 20, 25]

最佳答案

您可以使用 list comprehension :

my_list = [1, 2, 3, 4, 5]
my_new_list = [i * 5 for i in my_list]

>>> print(my_new_list)
[5, 10, 15, 20, 25]

请注意,列表推导式通常是执行 for 循环的更有效方式:

my_new_list = []
for i in my_list:
my_new_list.append(i * 5)

>>> print(my_new_list)
[5, 10, 15, 20, 25]

作为替代方案,这里有一个使用流行的 Pandas 包的解决方案:

import pandas as pd

s = pd.Series(my_list)

>>> s * 5
0 5
1 10
2 15
3 20
4 25
dtype: int64

或者,如果您只想要列表:

>>> (s * 5).tolist()
[5, 10, 15, 20, 25]

最后,一个可以使用map,尽管这通常是不被接受的。

my_new_list = map(lambda x: x * 5, my_list)

但是,使用 map 通常效率较低。根据 ShadowRanger 的评论关于这个问题的已删除答案:

The reason "no one" uses it is that, in general, it's a performancepessimization. The only time it's worth considering map in CPython isif you're using a built-in function implemented in C as the mappingfunction; otherwise, map is going to run equal to or slower than themore Pythonic listcomp or genexpr (which are also more explicit aboutwhether they're lazy generators or eager list creators; on Py3, yourcode wouldn't work without wrapping the map call in list). If you'reusing map with a lambda function, stop, you're doing it wrong.

他的另一条评论发布到 this reply :

Please don't teach people to use map with lambda; the instant youneed a lambda, you'd have been better off with a list comprehensionor generator expression. If you're clever, you can make map workwithout lambdas a lot, e.g. in this case, map((5).__mul__, my_list), although in this particular case, thanks to someoptimizations in the byte code interpreter for simple int math, [x * 5 for x in my_list] is faster, as well as being more Pythonic and simpler.

关于python - 如何将列表中的每个元素乘以一个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35166633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com