簡體   English   中英

如何獲取包含最接近給定元組的元組

[英]How to get the tuple which contains nearest tuple to a given tuple

我有一個元組列表:

x = [('abc', (7, 1, 8, 41), None), ('efg', (12, 2, 13, 42), None)]
element = (13, 2, 14, 78)

我需要獲取具有最接近“元素”的元組的元組。 即我需要為元素= (13,2,14,78)獲得答案為('efg', (12,2,13,42) ,None

如何在python中做到這一點?

非常簡單 讓我們逐步解決您的問題。

用2個元組 計算 匹配 ,得到最大值

maxCount = 0
index = 0
for i,item in enumerate(x):
  count = 0
  for a in element:
    if a in item[1]:
      count+=1
  if maxCount < count:
    index = i

print(x[i])

另一種方法是獲取ele & i[1] for i in xele & i[1] for i in x集的對稱差。 我們可以對每個新set及其來自的x的索引創建一個元組。 然后,我們可以從這里按len對新set進行排序,並采用set with the smallest len which is also the least different, and plug that into set with the smallestset with the smallest的are元組的索引部分which is also the least different, and plug that into x`中。

res = [(set(element) ^ set(i[1]), x.index(i)) for i in x]
res = sorted(res, key=lambda x: len(x[0]))
# ('efg', (12, 2, 13, 42), None)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM