简体   繁体   中英

Python - Compare the similarity of one number and a list of numbers

I am trying to compare the similarity between 1 number and a list of numbers, and not sure how to generate this problem?

I know how to compare the similarity of 2 inputs:

from difflib import SequenceMatcher 
def similar(a,b):
    return SequenceMatcher(None, a, b).ratio()

a = '123abc'   
b = '321321'  
similar(a,b) 

And now I want to compare the similarity/relevance between 1 number and a list of number, I tried:

A=[1,2,3,4,5,6,7]
B=2

from difflib import SequenceMatcher 
def similar(a,b):
    return SequenceMatcher(None, a, b).ratio()

similar (A,B)

And it does not give me what I want - it shows "'int' object is not iterable". I am trying to get the accuracy/confident of how the number (2) is matching with the list of A. Ideally in this case - if the number is 2, and the list if from 1-7 then similarity is 1, and if the number is 8 or 9 then similarity is 0.

Anyone has ideas of how to do it? I am a new python learner - Thank you in advance!

Make B a list of length 1 in order to make both objects the same type so they are comparable.

A=[1,2,3,4,5,6,7]
B=[2]

from difflib import SequenceMatcher 
def similar(a,b):
    return SequenceMatcher(None, a, b).ratio()

similar (A,B)

Have you tried replacing:

B=2

with:

B=[2]

?

Cheers.

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