如何在python中找到一个单词的lenn n的次数?
我试图在一个列表中找到一个单词等于一个设定长度的次数? 例如:'我的名字是ryan'和2,函数会返回2,因为一个单词长度为2的次数。我有:如何在python中找到一个单词的lenn n的次数?,python,string,Python,String,我试图在一个列表中找到一个单词等于一个设定长度的次数? 例如:'我的名字是ryan'和2,函数会返回2,因为一个单词长度为2的次数。我有: def LEN(a,b): 'str,int==>int' 'returns the number of words that have a len of b' c=a.split() res=0 for i in c: if len(i)==b: res=res+1 return(res) 但是这给了我一个r
def LEN(a,b):
'str,int==>int'
'returns the number of words that have a len of b'
c=a.split()
res=0
for i in c:
if len(i)==b:
res=res+1
return(res)
但是这给了我一个res为1的值,而不是以c的len通过第一个i。你的函数工作得很好,你只是
提前返回:
def LEN(a,b):
'str,int==>int'
'returns the number of words that have a len of b'
c= a.split()
res = 0
for i in c:
if len(i)==b:
res= res + 1
return(res) # return at the end
这相当于:
>>> text = 'my name is ryan'
>>> sum(len(w) == 2 for w in text.split())
2
您在for循环中返回res
,程序一旦命中该语句,就会立即停止执行。您可以将其移动到循环之外,也可以使用这种可能更具python风格的方法:
>>> text = 'my name is ryan'
>>> sum(1 for i in text.split() if len(i) == 2)
2
或更短但不太清晰(但和):
第二个函数基于这样一个事实,即True==1
那么:
>>> s = 'my name is ryan'
>>> map(len, s.split()).count(2)
2
+1用于创造力;)代码>。我以前从未见过这种方法。注意:要在py3k中使用这种方法,您必须使用list(map(…)。count
。在Python3中,您可以执行:sum(map((2)。\uuuueq,s.split())
,但这很好unclear@jamylak你的意思是sum(map((2)。\uuuuueq,map(len,s.split())
<代码>;)我不知道我怎么没看到。谢谢。@Volatility如果你说第二个不太清楚,我建议你读一下:@Volatility我希望它能让你相信它是清楚的:)@Volatility是的:)虽然我不知道你的答案为什么不被接受
>>> s = 'my name is ryan'
>>> map(len, s.split()).count(2)
2