2024-04-25 13:40:01 发布
网友
我有两张单子:
a = [1,2,3,4] b = [True,False,True,False]
我想得到a中对应于b中True的元素,不要使用for循环。 我使用map函数来解决它,但它出错了:
a
b
True
for
map
def f(x,y): if x: return y s = list(map(f,b,a))
s是[1, None, 3, None],我不想要None,我该怎么办?你知道吗
s
[1, None, 3, None]
None
可以使用filter删除None。你知道吗
filter
例如:
a = [1,2,3,4] b = [True,False,True,False] def f(x,y): if x: return y s = list(filter(None, map(f,b,a))) print(s)
输出:
[1, 3]
使用compress:
compress
from itertools import compress a = [1,2,3,4] b = [True,False,True,False] s = list(compress(a, b))
为什么不直接zipping2列出并选择对应于True的值呢?你知道吗
a = [1,2,3,4] b = [True,False,True,False] print([x for x, y in zip(a, b) if y])
可以使用
filter
删除None
。你知道吗例如:
输出:
使用
compress
:输出:
为什么不直接zipping2列出并选择对应于True的值呢?你知道吗
相关问题 更多 >
编程相关推荐