如何通过每个字符可以出现多少次的限制来过滤字符串?

时间:2018-12-30 23:47:02

标签: python

我正在尝试编写一个函数,该函数通过允许每个字符出现多少次的特定限制来过滤字符串列表。

例如,这是我的输入:

foo = ['BAR', 'BAAR', 'RABA', 'AAARB', ...]
characters = ['B', 'A', 'A', 'R']

输出应为:

['BAR', 'BAAR', 'RABA']

值AAARB被排除,因为它有3个A。包含值BAR是因为可以使用少于最大字符出现次数的值。

该过程应该高效,因为我的字符串输入列表包含约7300个项目,允许的字符列表始终包含12个字符。

1 个答案:

答案 0 :(得分:3)

您可以通过比较允许的字符和每个字符串中的字符的直方图来轻松完成此操作。例如:

import collections

def find_subsets_of(strings, allowed_chars):
    allowed = collections.Counter(allowed_chars)
    for string in strings:
        counts = collections.Counter(string)
        if all(counts[ch] <= allowed[ch] for ch in counts):
            yield string

result = list(find_subsets_of(foo, characters))