How to merge similar items in a list

后端 未结 6 594
花落未央
花落未央 2021-01-19 02:50

I haven\'t found anything relevant on Google, so I\'m hoping to find some help here :)

I\'ve got a Python list as follows:

[[\'hoose\', 200], [\"Ba         


        
6条回答
  •  盖世英雄少女心
    2021-01-19 02:54

    @Mark Longair I was getting some error in python 3.5, so I corrected them as below:

    import Levenshtein
    data = [['hoose', 200],
           ["Bananphone", 10],
           ['House', 200],
           ["Bonerphone", 10],
           ['UniqueValue', 777]]
    
    already_merged = []
    
    for word, score in data:
        added_to_existing = False
        for merged in already_merged:
            for potentially_similar in merged[0]:
                if Levenshtein.distance(word, potentially_similar) < 5:
                    merged[0].add(word)
                    merged[1] += score
                    added_to_existing = True
                    break
            if added_to_existing:
                break
        if not added_to_existing:
            already_merged.append([set([word]),score])
    
    print (already_merged)
    

    @Mark thanks for such easy solution.

提交回复
热议问题