[英]Higher order function in Python exercise
我学习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)
您的函数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如何比较字符串和整数?
关于代码的其余部分,您不应创建将字符串的长度映射到字符串本身的字典。
当您有两个长度相等的字符串时会发生什么? 您应该以另一种方式映射: strings
到它们的长度。
但更好的是:您甚至不需要创建字典:
filtered_words = filter(lambda: len(word) > n, words)
n
是一个字符串。 在使用前将其转换为int
:
n = int(raw_input("Display words, that longer than...\n"))
Python 2.x会尝试为没有有意义的排序关系的对象生成一致但任意的排序,以使排序更容易。 这被认为是一个错误,并且在向后不兼容的3.x版本中进行了更改; 在3.x中,这会引发TypeError
。
我不知道您的功能是做什么的,或者您认为它是做什么的,只是看着它让我头疼。
这是锻炼的正确答案:
def filter_long_words(input_list, n):
return filter(lambda s: len(s) > n, input_list)
我的答案:
def filter_long_words():
a = raw_input("Please give a list of word's and a number: ").split()
print "You word's without your Number...", filter(lambda x: x != a, a)[:-1]
filter_long_words()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.