Python – 奇数字符
有时,在使用Python字符串时,我们可能会遇到需要提取所有出现奇数次的字符串字符的问题。这个问题可以应用在数据域和日间编程等领域。让我们讨论可以执行此任务的某些方式。
Input : test_str = ‘geekforgeeks’
Output : [‘r’, ‘o’, ‘f’, ‘s’]
Input : test_str = ‘g’
Output : [‘g’]
方法 #1:使用defaultdict()
+ 列表理解 + 循环
上述功能的组合可以用来解决这个问题。在此,我们用整数初始化 defaultdict(),然后执行频率计数。列表推导用于提取所有奇数频率。
# Python3 code to demonstrate working of
# Odd Frequency Characters
# Using list comprehension + defaultdict()
from collections import defaultdict
# helper_function
def hlper_fnc(test_str):
cntr = defaultdict(int)
for ele in test_str:
cntr[ele] += 1
return [val for val, chr in cntr.items() if chr % 2 != 0]
# initializing string
test_str = 'geekforgeeks is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# Odd Frequency Characters
# Using list comprehension + defaultdict()
res = hlper_fnc(test_str)
# printing result
print("The Odd Frequency Characters are : " + str(res))
输出 :
The original string is : geekforgeeks is best for geeks
The Odd Frequency Characters are : ['k', 'i', 't', 'g', 'e', 'b']
方法 #2:使用列表理解 + Counter()
上述功能的组合可以用来解决这个问题。在此,我们使用 Counter() 来计算频率。
# Python3 code to demonstrate working of
# Odd Frequency Characters
# Using list comprehension + Counter()
from collections import Counter
# initializing string
test_str = 'geekforgeeks is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# Odd Frequency Characters
# Using list comprehension + Counter()
res = [ chr for chr, count in Counter(test_str).items() if count & 1 ]
# printing result
print("The Odd Frequency Characters are : " + str(res))
输出 :
The original string is : geekforgeeks is best for geeks
The Odd Frequency Characters are : ['k', 'i', 't', 'g', 'e', 'b']