我有一條帶有唯一 ID 和相關歐元值的記錄。現在我想得到與我定義的值匹配的第一個值組合。到目前為止,我只得到了值的組合,但我想在輸出中也有各個值的 ID。
- 實際結果:
List-> 20.5 10.0 12.0
- 期望的結果:
List-> 1:20.5 3:10.0 5:12.0
兩個單獨的串列也可以
這是我的第一種方法:
from itertools import combinations
import numpy as np
import pandas as pd
# initialize list of lists
data = [[1 , 20.5], [2 , 32.0], [3 , 10.0], [4 , 5.0], [5 , 12.0], [6 , 10.0], [7, 2.0], [8 , 1.0], [9 , 6.0], [10 , 3.0], [11, 2.0]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['ID', 'EUR'])
summed_amount = 42.5
# Get All Possible Combinations Of Numbers In List
for value in range(1, len(df) 1):
possible_combination = list(combinations(df['EUR'], value))
#get the first values which equals the desired amount (summed_amount)
li =[each for each in possible_combination if sum(each) == summed_amount]
if li:
print("List-> ", *li[0])
break
結果:
List-> 20.5 10.0 12.0
謝謝和親切的問候:)
uj5u.com熱心網友回復:
有一些方法可以做到這一點。您需要以某種方式使用它們的 id 存盤值。您可以為此在 pandas 中解決問題,或者使用您自己的自定義類做一個更優雅的解決方案。看一看:
class MyAmount(object):
def __init__(self, id, value):
self.id = id
self.value = value
def __radd__(self, other):
return self.value (other.value if isinstance(other, MyAmount) else other)
def __repr__(self):
return "{}: {}".format(self.id, self.value)
MyAmount在這里,我們使用自己的自定義邏輯創建自己的類。然后,我們可以MyAmount為每一行創建物件。
amounts = df.apply(lambda s: MyAmount(s.ID, s.EUR), axis=1)
現在,只需保留您的代碼,但請確保用于amounts查找組合。
possible_combination = list(amounts, value))
由于我們覆寫了__radd__魔術函式,sum(each)因此將對 的value屬性求和MyAmount。而且由于我們覆寫了__repr__,當您列印一個MyAmount物件時,您將顯示一個帶有 format 的字串id: value。
您可以根據需要自定義它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/488317.html
