该函数应该采用类似以下的字符串:
'kkikkd'
并返回字母列表及其重复值,即
[[k,2],[i,1],[k,2],[d,1]]
但是它不起作用。有什么想法吗?
def chnum(xtrr):
lis2 = []
for n in xtrr:
if lis2[0][0] == n:
continue
lis1 = [n]
for m in xtrr:
if n == m:
i += 1
lis1 += [i]
lis2 += [lis1]
return lis2
答案 0 :(得分:2)
您可以使用itertools.groupby
>>> from itertools import groupby
>>> s = 'kkikkd'
>>> [[k, len(list(v))] for k,v in groupby(s)]
[['k', 2], ['i', 1], ['k', 2], ['d', 1]]
或者,您也可以使用re.findall
来完成此操作
>>> import re
>>> [[k, len(v)] for v,k in re.findall(r'((.)\2*)', s)]
[['k', 2], ['i', 1], ['k', 2], ['d', 1]]
答案 1 :(得分:1)
如果我正确地回答了您的问题,那么您正在尝试将每个字符的数量保留在字符串中并将结果存储在列表中。暴力破解的方法是使用字典来跟踪字符和出现的次数。 这是代码:
st= "kkikkd"
l=[]
temp=1
for i in range(1,len(st)):
if st[i-1] == st[i]:
temp += 1
else:
l.append([st[i-1],temp])
temp= 1
if st[i] == st[i-1]:
temp += 1
l.append([st[i],temp])
输出:[['k',2],['i',1],['k',2],['d',1]]
答案 2 :(得分:-1)
首先,您的代码中存在2个问题
def chnum(xtrr):
lis2 = []
for n in xtrr:
if lis2[0][0] == n: # lis2 is empty. It does not have 0th element, much less another nested list.
# this will only check if n is in the first element of lis2, what about all the other elements?
continue
lis1=[n]
i = 0
for m in xtrr:
if n== m:
i+=1
lis1 += [i]
lis2 += [lis1]
return lis2
print(chnum('kkidduus'))
但是我建议不要使用python的功能来修复它。特别是它的字典 像这样:
def chnum(xtrr):
d = {n:0 for n in xtrr} # create a dict where keys are letters from input string
for n in xtrr:
d[n] += 1
# for each letter from input increment the dict's value for that letter
return d
print(chnum('kkidduus'))
您将看到此代码更加简洁和可读。
如果您真的坚持要以嵌套列表的形式获取结果,那么此词典也是一个不错的起点。事后l = [list(t) for t in chnum('kkidduus').items()]
编辑: OP希望在每次重复字母时都看到计数,因此可以修改上面的代码以适应该要求
def chnum(xtrr):
d = {n:0 for n in xtrr} # create a dict where keys are letters from input string
for n in xtrr:
d[n] += 1
# for each letter from input increment the dict's value for that letter
l = [[n, d[n]] for n in xtrr]
return l
print(chnum('kkidduus'))
使用字典还是有好处的,因为dict键被散列了,因此在计算字母出现时将具有速度优势