2

この関数の形式はnumLen(s、n)です。ここで、sは文字列、nは整数です。コードが行うことになっているのは、長さがnである文字列内の単語の数を返すことです。

numLen( "これはテストです"、4)

2つの単語は4文字なので、2を返します。

def numLen(s, n):
'''
takes string s and integer n as parameters and returns the number of words
in the string s that have length n
'''
return s.split()
if len(s) == n:
    return 'hello'

文字列をリストに分割し、そのリスト内の各単語の長さを確認しようとしましたが、うまくいかなかったようです。私が何とか得た最も遠いのは、長さコードが機能するかどうかを確認するために、4を14に置き換えたときに「hello」を返すことでした。

4

5 に答える 5

5

これを試して:

def numLen(s, n):
    return sum(1 for x in s.split() if len(x) == n)

ジェネレータ式を使用しています。次のように機能します。

  • まず、文字列sを使用して単語に分割しますsplit()
  • 次に、正確な長さの単語をフィルタリングしますn
  • 1条件を満たすものごとに追加します
  • そして最後にすべてを追加し1ます
于 2013-01-27T22:04:06.483 に答える
3

これはクラス用であると想定しているので、以下の例はそれを達成するための基本的な方法です(ただし、PythonicityのOscar Lopezのソリューションに+1します:))。

In [1]: def numLen(s, n):
   ...:     # Split your string on whitespace, giving you a list
   ...:     words = s.split()
   ...:     # Create a counter to store how many occurrences we find
   ...:     counter = 0
   ...:     # Now go through each word, and if the len == the target, bump the counter
   ...:     for word in words:
   ...:         if len(word) == n:
   ...:             counter += 1
   ...:     return counter
   ...: 

In [2]: numLen("This is a test", 4)
Out[2]: 2

In [3]: numLen("This is another test", 7)
Out[3]: 1

In [4]: numLen("And another", 12)
Out[4]: 0
于 2013-01-27T22:06:49.093 に答える
2
reduce(lambda a, w: a+(len(w)>=4), s.split(), 0)
于 2013-01-27T22:08:00.167 に答える
0

これは私のために働きます:

def numLen(s, n):
    num = 0
    for i in s.split():
        if len(i) == n:
            num += 1
    return num

これはあなたが何をしようとしているのですか?ただし、句読点(ピリオド、コンマなど)は考慮されません。

于 2013-01-27T22:17:47.730 に答える
0

このコードを使用すると、文の各単語から長さを取得できます。Python2.7を使用

a = raw_input("Please give a sentence: ").split() 
for i in range(len(a)):
   print "The Word, ", str(a[i]), " have,", str(len(a[i])), " lengths"

Python3.xの場合

 a = input("Please give a sentence: ").split() 
 for i in range(len(a)):
    print ("The Word, ", str(a[i]), " have,", str(len(a[i])), " lengths")   
于 2017-08-03T12:50:26.060 に答える