在Python中使用filter()筛选以特定字符开头的单词(如何使用带2个参数的筛选器)
我在这里有一个函数,可以从列表中筛选出以所需字符开头的所有单词在Python中使用filter()筛选以特定字符开头的单词(如何使用带2个参数的筛选器),python,filter,Python,Filter,我在这里有一个函数,可以从列表中筛选出以所需字符开头的所有单词 new_list = [] def filter_words(word_list, c): for word in word_list: if word.startswith(c): new_list.append(word) else: continue 这项工作很好-现在我正在尝试使用filter()方法 我试过这个 list(filter
new_list = []
def filter_words(word_list, c):
for word in word_list:
if word.startswith(c):
new_list.append(word)
else:
continue
这项工作很好-现在我正在尝试使用filter()方法
我试过这个
list(filter(filter\u words,lst))
但我遇到了以下错误:TypeError:filter\u woerter()缺少1个必需的位置参数:“c”
所以我试过这个
list(filter(filter_words,l,'h'))
但随后出现另一个错误:TypeError:filter需要2个参数,得到3个
那么,如何传递第二个参数呢?您的
filter\u words
函数已经将一个列表(好的,是一个iterable)作为参数,并自行进行过滤,因此将其传递给filter()
没有意义-filter()
需要一个函数,该函数从iterable中提取一个元素并返回一个布尔值(这通常被称为“谓词函数”)。请注意:
def word_starts_with(word, letter):
return word.startswith(letter)
然后,您必须使用lambda作为部分应用程序,因此字母是固定的:
filter(lambda word: word_starts_with("H"), yourlistofwords)
哪种FWIW实际上是一种复杂的写入方式:
filter(lambda word: word.startswith("H"), yourlistofwords)
哪一个更习惯于用列表理解来写:
[word for word in yourlistofwords if word.startswith("h")]
文档中说什么应该作为aguments传递?一个函数和一个iterable。我传递了一个函数和一个列表,不是吗?@Takuya2412传递给
filter
的函数需要是一个谓词,它应该接受一个参数,并返回一个布尔值,指示该参数是否应该保留在输出中。您的filter_words
显然与此契约不匹配,因为它包含两个参数,并且不返回任何内容。
[word for word in yourlistofwords if word.startswith("h")]