将字符串转换为具有规范的列表

时间:2012-11-04 11:56:04

标签: python string list

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

my_string= "google"

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

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

谢谢!

2 个答案:

答案 0 :(得分:8)

您可以使用groupby中的itertools

from itertools import groupby
my_string= "google"
[(c, len(list(i))) for c, i in groupby(my_string)]

答案 1 :(得分: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]]