0

リスト内の単語が設定された長さと等しい回数を見つけようとしていますか? たとえば、「私の名前は 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)

しかし、これで得られるのは res が 1 であり、len が c の最初の i を通過しません。

4

3 に答える 3

4

for ループ内にいると、プログラムreturn resはそのステートメントに到達するとすぐに実行を停止します。ループの外に移動するか、おそらくより Pythonic なアプローチを使用できます。

>>> text = 'my name is ryan'
>>> sum(1 for i in text.split() if len(i) == 2)
2

または、より短いが、少し明確ではありません(ただし推奨):

>>> sum(len(i) == 2 for i in text.split())
2

2 番目の関数は、次の事実に基づいています。True == 1

于 2013-04-21T03:12:13.917 に答える
3

あなたの機能は正常に動作します。あなたはただreturn早い段階でingしています:

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
于 2013-04-21T03:11:54.900 に答える
2

どうですか:

>>> s = 'my name is ryan'
>>> map(len, s.split()).count(2)
2
于 2013-04-21T03:13:31.053 に答える