使用fi时向函数传递两个参数

2024-09-30 02:19:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张单子。我想过滤掉没有最小长度的单词。我试过过滤,但显示出一些错误。我的密码是

def words_to_integer(x,y):
          return len(x)> y


print("enter the list of words : ")
listofwords =  [ str(x)  for x in input().split()]  #list of words 
minimumlength = print("enter the length ")          
z = list(filter(words_to_integer,(listofwords,minimumlength)))

print("words with length greater than ",minimumlength ,"are" ,z )

错误是

 z = list(filter(words_to_integer,(listofwords,minimumlength)))
 TypeError: words_to_integer() missing 1 required positional argument: 'y'

Tags: oftheto错误integerfilter单词length
3条回答

你应该看看^{}

from functools import partial

z = filter(partial(words_to_integer, y=minimumlength), listofwords)

partial(words_to_integer, y=minimumlength)是与words_to_integer相同的函数,但参数y固定在minimumlength

当你打这个的时候

list(filter(words_to_integer,(listofwords,minimumlength)))

python尝试执行以下操作:

z = []
if words_to_integer(listofwords):
    z.append(listofwords)
if words_to_integer(minimumlength):
    z.append(minimumlength)

它将失败,因为words_to_integer接受2个参数,但只给出了一个

你可能想要这样的东西:

z = []
for word in listofwords:
    if words_to_integer(word):
        z.append(word)

就像filter

z = list(filter(lambda word: words_to_integer(word, minimumlength), listofwords))

或者在另一个答案中使用partial

你不能那样做。您需要传递一个已经知道minimumlength的函数

一种简单的方法是使用lambda而不是独立函数:

filter(lambda x: len(x) > minimumlength, listofwords)

相关问题 更多 >

    热门问题