[英]Turning a string into a list with specifications
我想在python中創建一個我的字符串列表,它會顯示字母在字符串中連續顯示多少次。 例如:
my_string= "google"
我想創建一個如下所示的列表:
[['g', 1], ['o', 2], ['g', 1], ['l', 1], ['e', 1]]
謝謝!
您可以使用itertools中的 groupby :
from itertools import groupby
my_string= "google"
[(c, len(list(i))) for c, i in groupby(my_string)]
您可以使用正則表達式和字典來查找和存儲每個字母的最長字符串,如下所示
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]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.