Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我试图写一个字母重复计数函数,但它不起作用_Python - Fatal编程技术网

Python 我试图写一个字母重复计数函数,但它不起作用

Python 我试图写一个字母重复计数函数,但它不起作用,python,Python,函数应该采用如下字符串: '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:

函数应该采用如下字符串:

'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

您可以使用
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]]

如果我没有弄错您的问题,那么您正在尝试对字符串中的每个字符进行计数,并将结果存储在列表中。蛮力的做法是使用字典来记录字符及其出现的次数。 代码如下:

 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]

首先,代码中有两个问题

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的强大功能,而不是修复它。尤其是它的字典 像这样:

您将看到这段代码更加简洁易读。 如果您真的坚持以嵌套列表的形式获取结果,那么本词典也是一个很好的起点。只需在chnum('kkidduus').items()中为t列出(t)

编辑: 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键是散列的,因此在计算字母出现次数时具有速度优势

请将代码作为文本而不是图像发布。它使调试变得更容易。@kgemp,欢迎使用stackoverflow:)来帮助您,我们需要查看您的代码和您试图解决问题的尝试。如果您不确定如何提问,将提供帮助。如果您在回答代码中设置
string=“kkikd”
,并运行它,您将注意到它不会产生所需的结果。@jpeg我想我没有正确回答问题。请您解释一下问题好吗?我不确定我能否更好地解释问题,实际上,有人明确地问:OP搜索
[[k,2],[i,1],[k,2],[d,1]]
,作为
'kkikd'
的结果,即计算字符串中字母的连续重复次数,而不是字符串中字母的总计数。@jpeg谢谢,我得到了它。请检查我刚刚编辑的新代码,如果有不正确的地方,请告诉我。不客气。您的代码现在似乎生成了所需的答案。尽管如此,我还是建议您在回答代码中使用原始示例:
st=“kkikkd”
。这有助于OP和其他任何人的测试。如果您使用答案代码运行
print(chnum('kkikkd'))
,您会注意到它不会产生所需的结果。感谢它的工作,但问题是,如果您输入字符串'kkikd',它返回{k':4,'i':1,'d':1},而它应该返回{k':2,'d':1},我尽量不使用库。@kgemp除了标准库之外,我的答案中没有使用库
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'))