是否尝试删除列表元素,如果它小于阈值?

时间:2019-02-01 22:39:27

标签: python list

我有一个列表:

lst = ['aaaaabbbbb','yyyyaaaaaaxxx', 'eeeaaaaassaaa']

,我正在尝试查看列表索引的50%到60%之间是否包含“ a”。如果不是,则应删除索引。

这就是我得到的:

def remove_stuff(sequences, min_c, max_c):
   seq = cleanUp(display(sequences))   # used from another function that makes the list
   for i in seq:
        a = 'a'
        a_find = int(seq.count(a))
        length_seq = int(len(seq))
        average = ((a_find) / length_seq) * 100
        if average < min_c:
            seq.remove(i)
        elif average > max_c:
            seq.remove(i)
         else:
             pass

输出类似于:

['aaaaabbbbb'] # only one that satisfied between 50-60%

我该如何获得新的修改清单?

感谢您的帮助!

3 个答案:

答案 0 :(得分:3)

In [2]: lst = ['aaaaabbbbb','yyyyaaaaaaxxx', 'eeeaaaaassaaa']

In [3]: lst = [i for i in lst if 0.5<i.count('a')/len(i)<0.6]

In [4]: lst
Out[4]: ['aaaaabbbbb']

答案 1 :(得分:0)

您可以为此使用过滤器:

def condition_a(elem):
    count_of_a = elem.count('a')
    rate_of_a = count_of_a / len(elem)
    return 0.5 <= rate_of_a <= 0.6

lst = ['aaaaabbbbb','yyyyaaaaaaxxx', 'eeeaaaaassaaa']
list(filter(condition_a, lst))

答案 2 :(得分:0)

您可以定义一种根据条件(谓词)保留元素的方法:

def keep_if(predicate, iterable):
  for element in iterable:
    if predicate(element):
      yield element

然后定义一种测试条件的方法:

def is_between_50_60_percent(letter, string):
  perc = string.count(letter) / len(string)
  return perc >= 0.5 and perc <= 0.6

给出您的列表:

lst = ['aaaaabbbbb','yyyyaaaaaaxxx', 'eeeaaaaassaaa']

最后,您可以致电:

keep_if( lambda x: is_between_50_60_percent('a', x), lst)

res = keep_if( lambda x: is_between_50_60_percent('a', x), lst)
print(list(res)) #=> ['aaaaabbbbb']