2013-09-01 70 views
1

我学习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) 
+0

Python是不是口齿不清(不会写这样有代码或者虽然),如果你不”为获得最难解决问题的解决方案而获得额外的积分,请使用简单的,惯用的方法:'[input_list中的单词如果len(word)> n]'更清晰并且更容易理解no? – Voo

+0

@Voo:是的,但锻炼确实说他使用'filter()'。 –

+1

@Lennart点,家庭作业可能很愚蠢,但教授仍然喜欢,如果你这样做,就像他们说的那样);仍然悲惨地教人们蟒蛇这种方式。 – Voo

回答

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 

如果你好奇,为什么,这个问题有答案: How does Python compare string and int?


关于你的代码的其余部分,你不应该创建一个字符串到字符串本身的长度映射的字典。

当你有两个等长的字符串时会发生什么?你应该映射其他方式:strings到它们的长度。

但更重要的是:你甚至都不需要创建一个字典:

filtered_words = filter(lambda: len(word) > n, words) 
1

n是一个字符串。使用前将其转换为int

n = int(raw_input("Display words, that longer than...\n")) 

的Python 2.x的将试图产生一个对象的一致,但是,任意排序,没有有意义的顺序关系,使分类更加容易。这被认为是一个错误,并在向后不兼容的3.x版本中发生了变化;在3.x中,这会产生一个TypeError

0

我不知道你的函数做什么,或者你想这样做,只是看着它给了我一个头痛。

这里有一个正确的答案,你的锻炼:

def filter_long_words(input_list, n): 
    return filter(lambda s: len(s) > n, input_list) 
0

我的回答:

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()