如何将列表中的每个元素乘以一个数字? [英] How do I multiply each element in a list by a number?

查看:447
本文介绍了如何将列表中的每个元素乘以一个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表:

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

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

How can I multiply each element in my_list by 5? The output should be:

[5, 10, 15, 20, 25]

推荐答案

您可以只使用列表推导:

You can just use a 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循环的更有效方法:

Note that a list comprehension is generally a more efficient way to do a for loop:

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

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

作为替代方案,以下是使用流行的Pandas软件包的解决方案:

As an alternative, here is a solution using the popular Pandas package:

import pandas as pd

s = pd.Series(my_list)

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

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

Or, if you just want the list:

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

这篇关于如何将列表中的每个元素乘以一个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆