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 に答える