2 回答

TA貢獻1844條經驗 獲得超8個贊
“天真的”方法:
將字典添加到新的結果列表中。對于每個新的字典,檢查它是否與列表中已有的字典匹配。如果是這樣,請合并它們。如果沒有,將其添加到列表中:
res = [opt[0]]
for d_new in opt[1:]:
for d in res:
if d['expiry'] == d_new['expiry'] and d['strike'] == d_new['strike']:
#if (d['expiry'], d['strike']) == (d_new['expiry'], d_new['strike']):
d.update(d_new)
break
else:
res.append(d_new)
這使用了for/else在這里很有用的結構,因為我們只想在結果列表中沒有與任何其他字典匹配的情況下將新字典添加到列表中。如果找到匹配項,我們將合并它們,break并且else不會執行。
略有改進:
上述方法導致O(n^2)for 循環每個 dict 的所有 dicts 的時間復雜度(不完全是,但學術上這仍然是O(n^2))。expiry為了嘗試改進這一點,第二種方法可以是將具有相似且一次性的字典組合在一起strike( O(n)):
from collections import defaultdict
merged_dicts = defaultdict(dict)
for d in opt:
merged_dicts[(d['expiry'], d['strike'])].update(d)
res = list(merged_dicts.values())
這使用了collections.defaultdict在沒有太多if條件的情況下輕松合并字典。我們還使用dict的update方法實際合并它們。

TA貢獻1796條經驗 獲得超4個贊
一種相當簡單的方法是使用 pandas:
df = pd.DataFrame(opt)
df = df.drop_duplicates(subset = ["expiry", "strike"])
[ v.dropna().to_dict() for k,v in df.iterrows() ]
結果是 :
[{'expiry': '2020-06-26', 'strike': 138.5, 'p_bid': 0.4375, 'p_ask': 0.46875},
{'expiry': '2020-06-26', 'strike': 139.0, 'p_bid': 0.6875, 'p_ask': 0.71875},
{'expiry': '2020-07-22', 'strike': 139.0, 'p_bid': 1.015625, 'p_ask': 1.0625}]
請注意,在刪除重復項時,我保留了第一個元素。如果你想要的話,可以很容易地留下最后一個元素,但是使用:
df = df.drop_duplicates(subset = ["expiry", "strike"], keep="last")
在這種情況下,結果是:
[{'expiry': '2020-06-26', 'strike': 138.5, 'c_bid': 0.6875, 'c_ask': 0.734375},
{'expiry': '2020-06-26', 'strike': 139.0, 'c_bid': 0.4375, 'c_ask': 0.484375},
{'expiry': '2020-07-22', 'strike': 139.0, 'c_bid': 0.28125, 'c_ask': 0.3125}]
另一種方法是使用字典來減少“相似”值:
reduction_dict = {(x["expiry"], x["strike"]):x for x in opt }
list(reduction_dict.values())
添加回答
舉報