📌  相关文章
📜  Python – 出现在超过 K 个字符串中的字符

📅  最后修改于: 2022-05-13 01:54:23.734000             🧑  作者: Mango

Python – 出现在超过 K 个字符串中的字符

有时,在使用Python时,我们会遇到计算字符串中存在多少个字符的问题。但有时,我们可能会遇到一个问题,即我们需要获取至少出现在 K 个字符串中的所有字符。让我们讨论可以执行此任务的某些方式。

方法#1:使用set() + Counter() + items() + loop
上述功能的组合可用于执行此特定任务。在此,我们使用 Counter 和 set 来查找计数,用于限制字符重复。

# Python3 code to demonstrate 
# Characters which Occur in More than K Strings
# using set() + Counter() + loop + items()
from collections import Counter
from itertools import chain
  
def char_ex(strs, k):
    temp = (set(sub) for sub in strs)
    counts = Counter(chain.from_iterable(temp))
    return {chr for chr, count in counts.items() if count >= k}
  
# Initializing list
test_list = ['Gfg', 'ise', 'for', 'Geeks']
  
# printing original list
print("The original list is : " + str(test_list))
  
# Initializing K
K = 2
  
# Characters which Occur in More than K Strings
# using set() + Counter() + loop + items()
res = char_ex(test_list, K)
      
# printing result 
print ("Filtered Characters are : " + str(res))
输出 :
The original list is : ['Gfg', 'ise', 'for', 'Geeks']
Filtered Characters are : {'e', 'G', 's', 'f'}

方法 #2:使用字典理解 + set() + Counter()
这些功能的组合以与上述类似的方式执行此任务。不同之处在于我们使用字典理解来为问题提供紧凑的解决方案。

# Python3 code to demonstrate 
# Characters which Occur in More than K Strings
# using set() + Counter() + dictionary comprehension
from collections import Counter
  
# Initializing list
test_list = ['Gfg', 'ise', 'for', 'Geeks']
  
# printing original list
print("The original list is : " + str(test_list))
  
# Initializing K
K = 2
  
# Characters which Occur in More than K Strings
# using set() + Counter() + dictionary comprehension
res = {key for key, val in Counter([ele for sub in
          test_list for ele in set(sub)]).items()
          if val >= K}
      
# printing result 
print ("Filtered Characters are : " + str(res))
输出 :
The original list is : ['Gfg', 'ise', 'for', 'Geeks']
Filtered Characters are : {'e', 'G', 's', 'f'}