题目: 输入一个字符串 str, 输出第 m 个只出现过 n 次的字符,如在字符串 gbgkkdehh 中, 找出第2个只出现1 次的字符,输出结果:d
解决思路: 利用 collections 库的 Counter方法统计字符串每个单词出现的次数
from collections import Counter
a = 'gbgkkdehh'
m = 2 # 第m个
n = 1 # 出现次数n
b = Counter(a)
print(b)
print(dict(b))
# 找出所有的出现n的字符
print(dict(b).items())
s = []
for i, j in dict(b).items():
if j == n: # 出现n次
s.append(i)
print(s)
print(s[m - 1]) # 第m个索引是m-1
result:
"D:\Program Files\Python\python.exe" D:/pythonProject/auto_app/python_practice/1.2.py
Counter({'g': 2, 'k': 2, 'h': 2, 'b': 1, 'd': 1, 'e': 1})
{'g': 2, 'b': 1, 'k': 2, 'd': 1, 'e': 1, 'h': 2}
dict_items([('g', 2), ('b', 1), ('k', 2), ('d', 1), ('e', 1), ('h', 2)])
['b', 'd', 'e']
d
a = 'gbgkkdehh'
m = 2 # 第m个
n = 1 # 出现次数n
#方法2列表推导式
s1 = [i for i, j in dict(Counter(a)).items() if j ==n]
print(s1[m-1])
result:
"D:\Program Files\Python\python.exe" D:/pythonProject/auto_app/python_practice/1.2.py
d