0

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

我认为我的代码很好,但它不起作用。我使用了http://pythontutor.com,我看到一个问题是我的 var.next 和 current 始终保持相同的值。

有人有想法吗?

这是我的代码:

    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]]
4

3 回答 3

3

在这里使用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]]
于 2012-11-03T17:18:53.630 回答
1

Aswini 代码的更简单变体:

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

print lis  
于 2012-11-03T17:35:26.797 回答
0

你可以使用 defaultdict 很容易地做到这一点:

import collections

defaultdict=collections.defaultdict
count=defaultdict(int)
string="hello world"
for x in string:
    count[x]+=1

要将其显示在列表中,您可以执行以下操作:

count.items()

在这种情况下会返回:

[(' ', 1), ('e', 1), ('d', 1), ('h', 1), ('l', 3), ('o', 2), ('r', 1), ('w', 1)]
于 2012-11-03T17:38:40.340 回答