我正在尝试将生成的组合相乘并从中创建一个新列表。
这是我到目前为止所拥有的:
import pandas as pd
import itertools
data1 = [[0.1],[0.2],[0.3],[0.5]]
df = pd.DataFrame(data1, columns = ['weights'])
for x in combinations(df['weights'], 2):
print(x)
>>>
(0.1, 0.2)
(0.1, 0.3)
(0.1, 0.5)
(0.2, 0.3)
(0.2, 0.5)
(0.3, 0.5)
##I want to make a new list that shows the product of each combinations,
## example: for every (x,y) combo, do x*y and make a new list called z
预期输出应产生一个新列表:
0.02
0.03
0.05
0.06
0.1
0.15
最佳答案
您可以通过简单的列表理解来完成此操作,不必使用itertools
:
inlist = [(0.1, 0.2),
(0.1, 0.3),
(0.1, 0.5),
(0.2, 0.3),
(0.2, 0.5),
(0.3, 0.5)]
z = [round(elem[0]*elem[1],2) for elem in inlist]
print(z)
输出:
[0.02, 0.03, 0.05, 0.06, 0.1, 0.15]
但是,如果您想使用 itertools
,您可以使用 starmap
来完成。功能:
from itertools import starmap
inlist = [(0.1, 0.2),
(0.1, 0.3),
(0.1, 0.5),
(0.2, 0.3),
(0.2, 0.5),
(0.3, 0.5)]
z = list(starmap(lambda i,j: round(i*j,2), inlist))
print(z)
输出:
[0.02, 0.03, 0.05, 0.06, 0.1, 0.15]
关于python - 将 (X, Y) 组合列表相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56136330/