我正在尝试解决一个问题,其中用户输入一个字符串,说str =“ aaabbcc”和一个整数n =2。
因此该功能应该从str中删除出现“ n”次的字符,并仅输出“ aaa”。
我尝试了几种方法,但无法获得正确的输出。 是否可以使用任何正则表达式函数,任何递归函数或普通的旧迭代。
先谢谢了。
答案 0 :(得分:3)
使用itertools.groupby
例如:
from itertools import groupby
s = "aaabbcc"
n = 2
result = ""
for k, v in groupby(s):
value = list(v)
if not len(value) == n:
result += "".join(value)
print(result)
输出:
aaa
答案 1 :(得分:2)
from collections import Counter
counts = Counter(string)
string = "".join(c for c in string if counts[c] != 2)
编辑:等等,对不起,我错过了“连续”。这样将删除整个字符串中恰好出现两次的字符(适合您的示例,但不适合一般情况)。
连续过滤器稍微复杂一点,但是可行-只需先找到连续运行,然后过滤出长度为2的过滤器即可。
runs = [[string[0], 0]]
for c in string:
if c == runs[-1][0]:
runs[-1][1] += 1
else:
runs.append([c, 1])
string = "".join(c*length for c,length in runs if length != 2)
Edit2:正如其他答案正确指出的那样,第一部分由groupby
from itertools import groupby
string = "".join(c*length for c,length in groupby(string) if length != 2)
答案 2 :(得分:2)
您可以使用itertools.groupby
:
>>> s = "aaabbccddddddddddeeeee"
>>> from itertools import groupby
>>> n = 3
>>> groups = (list(values) for _, values in groupby(s))
>>> "".join("".join(v) for v in groups if len(v) < n)
'bbcc'
答案 3 :(得分:1)
In [15]: some_string = 'aaabbcc'
In [16]: n = 2
In [17]: final_string = ''
In [18]: for k, v in Counter(some_string).items():
...: if v != n:
...: final_string += k * v
...:
In [19]: final_string
Out[19]: 'aaa'
您需要:from collections import Counter
答案 4 :(得分:1)
from collections import defaultdict
def fun(string,n):
dic = defaultdict(int)
for i in string:
dic[i]+=1
check = []
for i in dic:
if dic[i]==n:
check.append(i)
for i in check:
del dic[i]
return dic
string = "aaabbcc"
n = 2
result = fun(string, n)
sol =''
for i in result:
sol+=i*result[i]
print(sol)
输出
aaa