计算字母并显示在列表中 [英] count letter and show in list

查看:75
本文介绍了计算字母并显示在列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从用户那里接收一个字符串,并将其显示在列表中,以便列表中的每个器官都包含[字母,它在一行中重复的数字].

I need to receive a string from the user, present it in list so each organ in the list contains [the letter, the number it repeat in a row].

我认为我的代码不错,但是没有用. 我使用了 http://pythontutor.com ,我发现一个问题是我的var.next和当前版本与始终保持相同的值.

I thought my code is good but it doesn't work. I used http://pythontutor.com and I saw that one the problem is that my var.next and current stay with the same value all the time.

人家有个主意吗?

这是我的代码:

    string = raw_input("Enter a string:")
    i=0
    my_list=[]
    current=string[i]
    next=string[i+1]
    counter=1
    j=0
    while i<range(len(string)) and next<=range(len(string)):

        if i==len(string)-1:
            break
        j+=1
        i+=1
        if current==next:
            counter+=1

        else:
            print my_list.append([string[i],counter])
            counter=1

输出:

Enter a string: baaaaab
As list: [['b', 1], ['a', 5], ['b', 1]]

推荐答案

使用 itertools.groupby() 此处:

>>> from itertools import groupby
>>> [[k, len(list(g))] for k, g in groupby("baaaaab")]
[['b', 1], ['a', 5], ['b', 1]]

或者不使用库:

strs = raw_input("Enter a string:")
lis = []
for x in strs:
   if len(lis) != 0:
      if lis[-1][0] == x:
         lis[-1][1] += 1
      else:
         lis.append([x, 1])
   else:
       lis.append([x, 1])         
print lis                   

输出:

Enter a string:aaabbbcccdef
[['a', 3], ['b', 3], ['c', 3], ['d', 1], ['e', 1], ['f', 1]]

这篇关于计算字母并显示在列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆