1

私はPythonを学んでいて、解決策の演習中に、関数filter()が空のリストを返し、その理由がわかりません。ここに私のソースコードがあります:

"""
Using the higher order function filter(), define a function filter_long_words()
that takes a list of words and an integer n and returns
the list of words that are longer than n.
"""

def filter_long_words(input_list, n):
    print 'n = ', n
    lengths = map(len, input_list)
    print 'lengths = ', lengths
    dictionary = dict(zip(lengths, input_list))
    filtered_lengths = filter(lambda x: x > n, lengths) #i think error is here
    print 'filtered_lengths = ', filtered_lengths
    print 'dict = ',dictionary
    result = [dictionary[i] for i in filtered_lengths]
    return result

input_string = raw_input("Enter a list of words\n")
input_list = []
input_list = input_string.split(' ')
n = raw_input("Display words, that longer than...\n")

print filter_long_words(input_list, n)
4

4 に答える 4

4

関数は正常filter_long_wordsに動作しますが、エラーは次の場合に発生します。

n = raw_input("Display words, that longer than...\n")
print filter_long_words(input_list, n)  

n整数ではなく文字列です。

残念ながら、Python では文字列は常に整数よりも「大きい」(ただし、比較するべきではありません!):

>>> 2 > '0'
False

理由が知りたい場合は、この質問に答えがあります: Python は文字列と int をどのように比較しますか?


コードの残りの部分については、文字列の長さを文字列自体にマップする辞書を作成しないでください。

同じ長さのひもが 2 つあるとどうなりますか? 逆stringsに、長さにマッピングする必要があります。

さらに良いことに、辞書を作成する必要さえありません。

filtered_words = filter(lambda: len(word) > n, words)
于 2013-09-01T11:22:37.627 に答える
0

あなたの機能が何をしているのか、あなたが何を考えているのかわかりません。見ているだけで頭が痛くなります。

これがあなたの演習に対する正しい答えです。

def filter_long_words(input_list, n):
    return filter(lambda s: len(s) > n, input_list)
于 2013-09-01T11:23:24.617 に答える