我学习Python并在解决方案时练习,function filter()返回空列表,我无法理解为什么。下面是我的源代码:Python练习中的高阶函数
"""
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)
Python是不是口齿不清(不会写这样有代码或者虽然),如果你不”为获得最难解决问题的解决方案而获得额外的积分,请使用简单的,惯用的方法:'[input_list中的单词如果len(word)> n]'更清晰并且更容易理解no? – Voo
@Voo:是的,但锻炼确实说他使用'filter()'。 –
@Lennart点,家庭作业可能很愚蠢,但教授仍然喜欢,如果你这样做,就像他们说的那样);仍然悲惨地教人们蟒蛇这种方式。 – Voo