Sorting A Python Dictionary After Running An Itertools Function
This question is the culmination of two pieces of code guided by two answers here on SO. The first question I had was how to compare similarity between two strings and I got a good
Solution 1:
Yes, you need to associate the pair (ID, name). For this you can use a dict, a tuple or even a class. For example using tuples your code 2 would change to:
persons = [('id1', "Peter parker"), ('id2' ,"Richard Parker"), ('id3' ,"Parker Richard"), ('id4' ,"Aunt May")]
similarity = [[p1, p2, string_similarity(p1[1], p2[1])]
for p1, p2 in itertools.combinations(persons, 2)]
similarity = sorted(similarity, key=lambda x: x[2], reverse=True)
for p1, p2, sim in similarity:
print"{} - {}: {}".format(p1, p2, sim) # p1[0], p2[0] to show ids only
You get:
('id2', 'Richard Parker') - ('id3', 'Parker Richard'): 0.833333333333
('id1', 'Peter parker') - ('id2', 'Richard Parker'): 0.545454545455
('id1', 'Peter parker') - ('id3', 'Parker Richard'): 0.545454545455
('id1', 'Peter parker') - ('id4', 'Aunt May'): 0.0
('id2', 'Richard Parker') - ('id4', 'Aunt May'): 0.0
('id3', 'Parker Richard') - ('id4', 'Aunt May'): 0.0
Post a Comment for "Sorting A Python Dictionary After Running An Itertools Function"