python列表对应元素相乘
时间: 2023-07-25 22:18:24 浏览: 55
可以使用循环遍历列表对应元素相乘,也可以使用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)
```
两个列表对应元素相乘
可以使用for循环遍历两个列表中的相同位置的元素,将它们相乘并将结果添加到一个新的列表中,示例如下:
```python
list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9, 10]
result = []
for i in range(len(list1)):
result.append(list1[i] * list2[i])
print(result)
```
输出结果为:`[6, 14, 24, 36, 50]`
另外,还可以使用zip函数将两个列表打包成一个元组列表,然后使用列表生成式遍历这个元组列表,计算每个元组中两个元素的乘积,并将结果添加到一个新的列表中,示例如下:
```python
list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9, 10]
result = [x * y for x, y in zip(list1, list2)]
print(result)
```
输出结果为:`[6, 14, 24, 36, 50]`
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)