如何变换字符串以获得三个字母的数量?
例如,将字符串"i like walking"
称为""i l", " li", "lik" "
,依此类推?
如果我想知道我总共有多少计数并列出每个计数出现的次数怎么办?
答案 0 :(得分:9)
一个简单的列表理解:
s = "i like walking"
triplets = [s[i:i+3] for i in range(len(s) - 2)]
答案 1 :(得分:5)
s = "i like walking"
print [s[i:i+3] for i in xrange(0, len(s) - 2)]
答案 2 :(得分:4)
以下是列表推导的替代方法:
>>> s = "i like walking"
>>> map(''.join, zip(s, s[1:], s[2:]))
['i l', ' li', 'lik', 'ike', 'ke ', 'e w', ' wa', 'wal', 'alk', 'lki', 'kin', 'ing']
答案 3 :(得分:1)
>>> strs="i like walking"
>>> pair_size=3
>>> [strs[i:i+pair_size] for i in range(len(strs)-(pair_size-1))]
['i l', ' li', 'lik', 'ike', 'ke ', 'e w', ' wa', 'wal', 'alk', 'lki', 'kin', 'ing']
>>> pair_size=4
>>> [strs[i:i+pair_size] for i in range(len(strs)-(pair_size-1))]
['i li', ' lik', 'like', 'ike ', 'ke w', 'e wa', ' wal', 'walk', 'alki', 'lkin', 'king']
答案 4 :(得分:0)
这样的事情应该有效:
result = []
for i in range(0,len(yourString) - 2):
temp = yourString[i] + yourString[i+1] + yourString[i+2]
result.append(temp)
答案 5 :(得分:0)
还有一种方法:
mystr="i like walking"
mylist=[]
i=0
while i<len(mystr)-2:
mylist.append(mystr[i:i+3])
i+=1
print mylist