小编use*_*364的帖子

如何使此列表功能更快?

def removeDuplicatesFromList(seq): 
    # Not order preserving 
    keys = {}
    for e in seq:
        keys[e] = 1
    return keys.keys()

def countWordDistances(li):
    '''
    If li = ['that','sank','into','the','ocean']    
    This function would return: { that:1, sank:2, into:3, the:4, ocean:5 }
    However, if there is a duplicate term, take the average of their positions
    '''
    wordmap = {}
    unique_words = removeDuplicatesFromList(li)
    for w in unique_words:
        distances = [i+1 for i,x in enumerate(li) if x == w]
        wordmap[w] = float(sum(distances)) / float(len(distances)) #take average
    return wordmap …
Run Code Online (Sandbox Code Playgroud)

python algorithm optimization dictionary list

7
推荐指数
3
解决办法
698
查看次数

标签 统计

algorithm ×1

dictionary ×1

list ×1

optimization ×1

python ×1