簡體   English   中英

Python練習中的高階函數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM