简体   繁体   English

根据条件删除列表的元素

[英]Deleting elements of a list based on a condition

I have a list of elements from which I want to remove those elements whose count is less than or equal to 2 in all the list.我有一个元素列表,我想从中删除所有列表中计数小于或等于 2 的元素。

For example:例如:

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

I want to remove 'a' , 'd' , 'f' , 'g' from A and store the rest in B so that the list becomes:我想从A删除'a''d''f''g'并将其余部分存储在B以便列表变为:

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

I created a dictionary which will store all the count of elements and based on that I want to remove the elements with count less than or equal to 2.我创建了一个字典,它将存储所有元素的计数,并基于此我想删除计数小于或等于 2 的元素。

Below is the code which I have written so far.下面是我到目前为止编写的代码。

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]

You can use collections.Counter :您可以使用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]

Output:输出:

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

Before you add a new key to the dictionary , you have to check if the key exists .在向字典中添加新之前,您必须检查该键是否存在 If not, just add the key to the dictionary .如果没有,只需将添加到字典中 Otherwise, update the key's value.否则,更新键的值。

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

Then filter the initial list using the created dictionary.然后使用创建的字典过滤初始列表。

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

Output输出

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM