简体   繁体   中英

How to get the tuple which contains nearest tuple to a given tuple

I have a list of tuples:

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

I need to fetch the tuple that has the tuple which is nearest to the 'element'. ie I need to get the answer as ('efg', (12, 2, 13, 42), None) for element = (13,2,14,78)

How can I do this in python?

It's very simple. Let take step by step to clear your question.

It is count the matches by 2 tuple and get the max .

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])

A different approach would be to get the symmetric differences of the sets of ele & i[1] for i in x . We could make a tuple with each new set and the index of x it came from. From here we could then sort the new set by len and take the index part of are tuple with the set with the smallest len 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM