代码之家  ›  专栏  ›  技术社区  ›  Jack Arnestad

仅当在X个其他子列表中存在时保留嵌套列表中的项

  •  0
  • Jack Arnestad  · 技术社区  · 7 年前

    test = [['hello', 'hola'], ['hello, 'bonjour', 'hola'], ['hello', 'ciao', 'namaste'], ['hola', 'ciao'], ['hola', 'ciao], ['namaste', 'bonjour', 'bonjour']]
    

    如果每个子列表中至少有X个子列表不存在,那么我有兴趣从每个子列表中删除所有元素(共享词,共享定义阈值)。对于本例,如果我们设置x=3,则只有值“hello”、“hola”和“ciao”将保留在任何列表中,从而得出:

    shared = [['hello', 'hola'], ['hello, 'hola'], ['hello', 'ciao'], ['hola', 'ciao'], ['hola', 'ciao], []]
    

    怎么能做到?我在这里放了一些代码,但是作为初学者,我在编写Python登录时迷失了方向。

    1 回复  |  直到 7 年前
        1
  •  2
  •   user3483203    7 年前

    collections.Counter 在扁平列表中,使用集合忽略单个子列表中的重复值:

    appearances = Counter(word for sub in arr for word in set(sub))
    # Counter({'hola': 4, 'hello': 3, 'ciao': 3, 'bonjour': 2, 'namaste': 2})
    

    [[word for word in sub if appearances[word] >= threshold] for sub in arr]
    

    from collections import Counter
    
    def threshold_filter(arr, threshold):
      appearances = Counter(word for sub in arr for word in set(sub))
    
      return [
        [word for word in sub if appearances[word] >= threshold] 
        for sub in arr
      ]
    
    print(threshold_filter(test, 3))
    
    # Result 
    [['hello', 'hola'], ['hello', 'hola'], ['hello', 'ciao'], ['hola', 'ciao'], ['hola', 'ciao'], []]