2

我想在 python 中从我的字符串中创建一个列表,它会告诉我一个字母在字符串中连续显示多少次。例如:

my_string= "google"

我想创建一个如下所示的列表:

[['g', 1], ['o', 2], ['g', 1], ['l', 1], ['e', 1]]

谢谢!

4

2 回答 2

8

您可以使用itertools中的groupby

from itertools import groupby
my_string= "google"
[(c, len(list(i))) for c, i in groupby(my_string)]
于 2012-11-04T12:04:04.337 回答
0

您可以使用正则表达式和字典来查找和存储每个字母的最长字符串,如下所示

s = 'google'
nodubs = [s[0]] + [s[x] if s[x-1] != s[x] else '' for x in range(1,len(s))]
nodubs = ''.join(nodubs)
import re
dic = {}
for letter in set(s):
    matches = re.findall('%s+' % letter, s)
    longest = max([len(x) for x in matches])
    dic[letter] = longest

print [[n,dic[n]] for n in nodubs]

结果:

[['g', 1], ['o', 2], ['g', 1], ['l', 1], ['e', 1]]
于 2012-11-04T12:01:32.987 回答