我想在 python 中从我的字符串中创建一个列表,它会告诉我一个字母在字符串中连续显示多少次。例如:
my_string= "google"
我想创建一个如下所示的列表:
[['g', 1], ['o', 2], ['g', 1], ['l', 1], ['e', 1]]
谢谢!
您可以使用正则表达式和字典来查找和存储每个字母的最长字符串,如下所示
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]]