我在将地图转换为列表时遇到问题,当它可以转换为设置时
list_nums_2 = [2, 4, 5, 9, 8, 7, 6, 3, 1, 0]
evens = filter(lambda a: a % 2 == 0, list_nums_2)
print(set(evens)) # Out: {0, 2, 4, 6, 8}
print(list(evens)) # Out: []
Run Code Online (Sandbox Code Playgroud)
我知道这不是因为它已经从下面转换为设置,很明显set可以转换为list
set_1 = {2, 3, 4, 5, 6}
print(list(set_1)) # Out: [2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)
当你运行set(evens)它时,它会消耗filter对象中的所有项目.因此,执行时没有可用的项目,list(evens)并返回空列表.
该filter对象是一个迭代器,它是可迭代的,因此您可以调用next()它来获取下一个项目:
>>> evens = filter(lambda a: a % 2 == 0, list_nums_2)
>>> evens
<filter object at 0x7f2f4c309710>
>>> next(evens)
2
>>> next(evens)
4
>>> next(evens)
8
>>> next(evens)
6
>>> next(evens)
0
>>> next(evens)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
Run Code Online (Sandbox Code Playgroud)
例外是因为filter对象中没有更多项.
| 归档时间: |
|
| 查看次数: |
333 次 |
| 最近记录: |