我正在尝试编写一个字母重复计数功能,但它不起作用

要记录时间,您可以使用time命令 (Unix)。


例如,如果我运行这个程序:


iterations = 0

while True:

        // do something

        iterations+=1

        print iterations 

使用以下命令调用脚本:


时间 python myscript.py


之后,假设您使用Cntr+C或任何其他强制停止来停止执行。您现在可以通过检查输出来检查运行脚本的时间以及获得的迭代次数,在我的情况下为:


7773

7774

7775

Traceback (most recent call last):

  File "script.py", line 5, in <module>

    print counter

KeyboardInterrupt



real    0m2.447s

user    0m0.109s

sys     0m0.234s

请注意,您可以在time命令的文档中找到从中获得的三个时间值的含义


茅侃侃
浏览 124回答 3
3回答

鸿蒙传说

如果我正确地回答了您的问题,那么您正在尝试对字符串中的每个字符进行计数并将结果存储在列表中。蛮力的做法是使用字典来跟踪字符和它出现的次数。这是代码:&nbsp;st= "kkikkd"&nbsp;l=[]&nbsp;temp=1&nbsp;for i in range(1,len(st)):&nbsp; &nbsp; if st[i-1] == st[i]:&nbsp; &nbsp; &nbsp; &nbsp; temp += 1&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; l.append([st[i-1],temp])&nbsp; &nbsp; &nbsp; &nbsp; temp= 1if st[i] == st[i-1]:&nbsp; &nbsp; temp += 1l.append([st[i],temp])输出: [['k', 2], ['i', 1], ['k', 2], ['d', 1]]

摇曳的蔷薇

您可以使用 itertools.groupby>>> from itertools import groupby>>> s = 'kkikkd'&nbsp;>>> [[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]]

神不在的星期二

首先,您的代码中有两个问题def chnum(xtrr):&nbsp; &nbsp; lis2 = []&nbsp; &nbsp; for n in xtrr:&nbsp; &nbsp; &nbsp; &nbsp; if lis2[0][0] == n:&nbsp; # lis2 is empty. It does not have 0th element, much less another nested list.&nbsp; &nbsp; &nbsp; &nbsp; # this will only check if n is in the first element of lis2, what about all the other elements?&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; lis1=[n]&nbsp; &nbsp; &nbsp; &nbsp; i = 0&nbsp; &nbsp; &nbsp; &nbsp; for m in xtrr:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if n== m:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i+=1&nbsp; &nbsp; &nbsp; &nbsp; lis1 += [i]&nbsp; &nbsp; &nbsp; &nbsp; lis2 += [lis1]&nbsp; &nbsp; &nbsp;return lis2print(chnum('kkidduus'))但是我建议不要修复它,而是建议使用 python 的强大功能。特别是它的字典像这样:def chnum(xtrr):&nbsp; &nbsp; d = {n:0 for n in xtrr}&nbsp; # create a dict where keys are letters from input string&nbsp; &nbsp; for n in xtrr:&nbsp; &nbsp; &nbsp; &nbsp; d[n] += 1&nbsp; &nbsp; &nbsp; &nbsp; # for each letter from input increment the dict's value for that letter&nbsp; &nbsp; return dprint(chnum('kkidduus'))您将看到这段代码更加简洁和易读。如果您真的坚持要以嵌套列表的形式获得结果,那么这本词典也是一个很好的起点。l = [list(t) for t in chnum('kkidduus').items()]事后做编辑:OP希望在每次重复字母时查看计数,因此可以修改上面的代码以适应def chnum(xtrr):&nbsp; &nbsp; d = {n:0 for n in xtrr}&nbsp; # create a dict where keys are letters from input string&nbsp; &nbsp; for n in xtrr:&nbsp; &nbsp; &nbsp; &nbsp; d[n] += 1&nbsp; &nbsp; &nbsp; &nbsp; # for each letter from input increment the dict's value for that letter&nbsp; &nbsp; l = [[n, d[n]] for n in xtrr]&nbsp; &nbsp; return lprint(chnum('kkidduus'))使用字典在这里仍然有好处,因为 dict 键是散列的,因此在计算字母出现时具有速度优势
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python