【问题标题】:Deleting elements of a list based on a condition根据条件删除列表的元素
【发布时间】:2018-10-12 10:42:54
【问题描述】:

我有一个元素列表,我想从中删除所有列表中计数小于或等于 2 的元素。

例如:

A = [['a','b','c'],['b','d'],['c','d','e'],['c','e','f'],['b','c','e','g']]

我想从A 中删除'a''d''f''g' 并将其余部分存储在B 中,以便列表变为:

B = [['b','c'],['b'],['c','e'],['c','e'],['b','c','e']]

我创建了一个字典,它将存储所有元素的计数,并基于此我想删除计数小于或等于 2 的元素。

下面是我目前写的代码。

for i in range(len(A)):
    for words in A[i]:
        word_count[words] +=1
    B = [A[i] for i in range(len(A)) if word_count[words]<2]

【问题讨论】:

    标签: python list


    【解决方案1】:

    你可以使用collections.Counter:

    from collections import Counter
    import itertools
    A = [['a','b','c'],['b','d'],['c','d','e'],['c','e','f'],['b','c','e','g']]
    c = Counter(itertools.chain(*A))
    new_a = [[b for b in i if c[b] > 2] for i in A]
    

    输出:

    [['b', 'c'], ['b'], ['c', 'e'], ['c', 'e'], ['b', 'c', 'e']]
    

    【讨论】:

    • @BcK 感谢您的帮助。它对我有用。此外,如果我想在 c 中存储百分比然后选择大于 40 的百分比,那么在同一个列表中而不是 count 中,我该怎么做,即在 c 中存储百分比。
    • total = sum(c.values()); for k, v in c.items(): c[k] = v / total 这样的东西应该可以工作@AnkitaPatnaik
    • 这是一个非常好的改变答案,我赞成。作为一项改进,请考虑使用chain.from_iterable(A) 而不是chain(*A),因为前者效率更高。
    【解决方案2】:

    在向字典添加新的之前,您必须检查键是否存在。如果没有,只需将 key 添加到 dictionary。否则,更新键的值。

    A = [['a','b','c'],['b','d'],['c','d','e'],['c','e','f'],['b','c','e','g']]
    word_count = {}
    for i in range(len(A)):
      for words in A[i]:
        if words not in word_count:
          word_count[words] = 0
        word_count[words] += 1
    

    然后使用创建的字典过滤初始列表。

    B = [[x for x in A[i] if word_count[x] > 2] for i in range(len(A))]
    print(B)
    

    输出

    [['b', 'c'], ['b'], ['c', 'e'], ['c', 'e'], ['b', 'c', 'e']]
    

    【讨论】:

    • if words not in word_count: word_count[words] = 0 的小快捷方式 --> word_count.setdefault(words, 0)
    猜你喜欢
    • 2011-11-29
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多