Python '的目的是什么;列表';过滤函数之前的函数?
过滤函数之前的“列表”函数的用途是什么Python '的目的是什么;列表';过滤函数之前的函数?,python,Python,过滤函数之前的“列表”函数的用途是什么 # Program to filter out only the even items from a list my_list = [1, 5, 4, 6, 8, 11, 3, 12] new_list = list(filter(lambda x: (x%2 == 0) , my_list)) print(new_list) 它将迭代器转换为list,类似于int、str、float,等等。list()函数获取filter()返回的迭代器对象,使用
# Program to filter out only the even items from a list
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)
它将迭代器转换为
list
,类似于int
、str
、float
,等等。list()函数获取filter()返回的迭代器对象,使用它并将其写入列表。因此,您还可以执行诸如new_list[10]和len(new_list)之类的操作,这在没有list()函数的情况下是不可能的。因为在python 3+中,返回的是iterable而不是list。尽管在这些情况下更倾向于使用列表理解,因为它们更快更容易阅读
new_list = [x for x in my_list if not x % 2]
将调用
filter
的结果转换为列表。filter
返回迭代器<代码>列表使用该迭代器生成的元素,并将它们放入一个集合-列表中。@mkrieger1否,请以另一种方式向我解释,因为我不明白。我不确定你不明白什么。您是否尝试过删除list()
?你看到有区别吗?是的,现在我明白了,它返回: