我在寻找CoinBuy Quote和CoinSell Quote之间的匹配。
我已经能够计算实例,当其中一个或多个实例出现6次时,我知道我在所有6个选项中都有匹配。这太棒了。
但当我努力把“CoinBuy‘s和CoinSell’s
all_options = [
{'CoinBuy': 1, 'Base': 'DEXE', 'Quote': {'USDT', 'ETH', 'BUSD'}},
{'CoinBuy': 2, 'Base': 'BOND', 'Quote': {'USDT', 'BTC', 'BUSD'}},
{'CoinBuy': 3, 'Base': 'STX', 'Quote': {'USDT', 'BTC', 'BUSD'}},
{'CoinSell': 1, 'Base': 'NAS', 'Quote': {'ETH', 'BTC'}},
{'CoinSell': 2, 'Base': 'CHESS', 'Quote': {'USDT', 'BTC', 'BUSD'}},
{'CoinSell': 3, 'Base': 'REP', 'Quote': {'USDT', 'ETH', 'BTC', 'BUSD'}}
]预期成果:
Matches
CoinBuy 1 & CoinSell 3 in common 'ETH'
CoinBuy 2 & CoinSell 2 in common 'USDT', 'BTC', 'BUSD'
CoinBuy 3 & CoinSell 1 in common 'BTC', 'BUSD'发布于 2021-12-08 23:05:24
这完全有可能:
dx = dict()
for opt in all_options:
for quote in opt.get('Quote'):
ls = dx.get(quote, [])
ls.append(opt)
dx[quote] = ls
commonalities = {}
for exchange, opts in dx.items():
for i in range(len(opts)):
left = opts[i]
for j in range(i+1,len(opts)):
right = opts[j]
buy_index = sell_index = None
if 'CoinBuy' in left and 'CoinSell' in right:
buy_index = left.get('CoinBuy')
sell_index = right.get('CoinSell')
elif 'CoinBuy' in right and 'CoinSell' in left:
buy_index = right.get('CoinBuy')
sell_index = left.get('CoinSell')
# Both other cases are invalid pairs
if buy_index and sell_index:
commonality = commonalities.get((buy_index, sell_index), [])
commonality.append(exchange)
commonalities[(buy_index, sell_index)] = commonality
for commonality, exchanges in commonalities.items():
buy_index, sell_index = commonality
excs = ", ".join((f"'{e}'" for e in exchanges))
print(f"CoinBuy {buy_index} & CoinSell {sell_index} in common {excs}")话虽如此,以上这些都是相当尴尬的,而且相当残忍。基本算法是:
输出结果如下:
>>> for commonality, exchanges in commonalities.items():
... buy_index, sell_index = commonality
... excs = ", ".join((f"'{e}'" for e in exchanges))
... print(f"CoinBuy {buy_index} & CoinSell {sell_index} in common {excs}")
...
CoinBuy 1 & CoinSell 2 in common 'USDT', 'BUSD'
CoinBuy 1 & CoinSell 3 in common 'USDT', 'BUSD', 'ETH'
CoinBuy 2 & CoinSell 2 in common 'USDT', 'BUSD', 'BTC'
CoinBuy 2 & CoinSell 3 in common 'USDT', 'BUSD', 'BTC'
CoinBuy 3 & CoinSell 2 in common 'USDT', 'BUSD', 'BTC'
CoinBuy 3 & CoinSell 3 in common 'USDT', 'BUSD', 'BTC'
CoinBuy 1 & CoinSell 1 in common 'ETH'
CoinBuy 2 & CoinSell 1 in common 'BTC'
CoinBuy 3 & CoinSell 1 in common 'BTC'我提出这个问题而不是(更恰当地说)让您先尝试一下的唯一原因是,翻转索引的直觉并不常见,但它可以使这种处理更加容易。此外,它还演示了原始数据结构有多尴尬(为什么是“CoinBuy”和“CoinSell”键而不是另一个键的值,比如“transaction_type”?)以及它最终强加给你多少额外的逻辑。
尽管如此,这个解决方案不太可能在很多比较(考虑嵌套循环的数量)下支持。您可能想考虑如何将原始数据结构转换为更容易回答您所寻找的问题的内容。或者将所有这些都放在数据库中,并使用适当的查询。
https://stackoverflow.com/questions/70282281
复制相似问题