Python 使用“switch\u var”切换“filter”函数以收集“False”元素的最佳方法是什么?
使用我的switch_var切换filter函数以收集错误元素的最佳方法是什么 我想 如果switch_var为False,则collect tuple first元素为True 如果switch_var为True,则collect tuple first元素为False 目前我是这样实现的Python 使用“switch\u var”切换“filter”函数以收集“False”元素的最佳方法是什么?,python,filter,boolean,Python,Filter,Boolean,使用我的switch_var切换filter函数以收集错误元素的最佳方法是什么 我想 如果switch_var为False,则collect tuple first元素为True 如果switch_var为True,则collect tuple first元素为False 目前我是这样实现的 switch_var = False lst = [(True, "A"), (False, "B")] if not switch_var: filter(lambda x: x[0], lst)
switch_var = False
lst = [(True, "A"), (False, "B")]
if not switch_var:
filter(lambda x: x[0], lst)
else:
filter(lambda x: not x[0], lst)
但我想要像这样的方式
switch_var = True
filter(lambda b: switch_var b, lst)
有这样的方法吗?你很接近。只需在过滤器函数中添加开关布尔值即可
filterlambda x:x[0]==未切换变量,lst您非常接近。只需在过滤器函数中添加开关布尔值即可 filterlambda x:x[0]==不切换变量,lst替代方法:
import itertools
switch_var = False
lst = [(True, "A"), (False, "B")]
result = list(itertools.filterfalse(lambda x: x[0] == switch_var, lst))
备选办法:
import itertools
switch_var = False
lst = [(True, "A"), (False, "B")]
result = list(itertools.filterfalse(lambda x: x[0] == switch_var, lst))