python列表内元素相乘
时间: 2023-06-08 09:06:11 浏览: 150
可以使用 for 循环或者 reduce 函数实现 Python 列表内元素相乘。
使用 for 循环的代码如下所示:
```
my_list = [1, 2, 3, 4, 5]
result = 1
for num in my_list:
result *= num
print(result)
```
使用 reduce 函数的代码如下所示:
```
from functools import reduce
my_list = [1, 2, 3, 4, 5]
result = reduce((lambda x, y: x * y), my_list)
print(result)
```
相关问题
python列表对应元素相乘
可以使用循环遍历列表对应元素相乘,也可以使用Python内置函数`reduce()`。
循环遍历示例代码:
```
lst = [2, 3, 4, 5]
result = 1
for num in lst:
result *= num
print(result)
```
输出结果为:120
使用`reduce()`函数示例代码:
```
from functools import reduce
lst = [2, 3, 4, 5]
result = reduce(lambda x, y: x*y, lst)
print(result)
```
输出结果为:120
需要注意的是,使用`reduce()`函数需要先导入`functools`模块。
python列表元素依次相乘
以下是两种Python列表元素依次相乘的方法:
1. 使用numpy库进行数组相乘,然后使用sum函数求和。
```python
import numpy as np
ls = [111, 222, 333, 444, 555, 666, 777, 888, 999]
lt = [999, 777, 555, 333, 111, 888, 666, 444, 222]
result = np.array(ls) * np.array(lt)
print(sum(result))
```
2. 使用for循环遍历两个列表,依次取出对应位置的元素相乘,然后累加求和。
```python
ls = [111, 222, 333, 444, 555, 666, 777, 888, 999]
lt = [999, 777, 555, 333, 111, 888, 666, 444, 222]
result = 0
for i in range(len(ls)):
result += ls[i] * lt[i]
print(result)
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)