Skip to main content
 首页 » 编程设计

python之如何使用运算符 'and' 和/或 'or' 映射两个过滤列表

2024年10月01日8Terrylee

我有以下两个列表:

advanced_filtered_list_val1 = [row for row in cleaned_list if float(row[val1]) < wert1] 
 
advanced_filtered_list_val2 = [row for row in cleaned_list if float(row[val2]) < wert2] 

如何使用选项和/或或将过滤后的列表映射到列表中?

列表中的数据是字典,我在这个列表中搜索和过滤一些行。我想过滤两个值。这很好用。但是我现在如何将其映射到列表中的过滤器?

我尝试了以下操作:

select = int(input()) 
 
#and operation 
if select == 1: 
    mapped_list = [row for row in advanced_filtered_list_val1 and advanced_filtered_list_val2] 
    for x in mapped_list: 
        print(x) 
#or operation 
if select == 2: 
    mapped_list = [row for row in advanced_filtered_list_val1 or advanced_filtered_list_val2] 
    for x in mapped_list: 
        print(x) 

我导入数据如下:

faelle = [{k: v for k, v in row.items()} 
 
 
for row in csv.DictReader(csvfile, delimiter=";")] 

我现在想从 wert1 和 wert2 以及 wert1 或 wert2 进行过滤。这意味着在 and 子句上它应该在两个过滤器 true 上,而在 or 子句上它应该是 wert1 或 wert2 True

请您参考如下方法:

您想过滤 cleaned_list 中包含的字典,这些字典符合两个类似 wert 的条件 (AND) 或至少其中之一 (OR)。你能做的是

import operator as op 
ineq_1    = 'gt' 
ineq_2    = 'lt' 
select    = 2 
andor = { 
    1:lambda L: filter( 
        lambda d: getattr(op,ineq_1)(float(d[val1]), wert1) 
                  and getattr(op,ineq_2)(float(d[val2]), wert2), 
        L 
    ), 
    2:lambda L: filter( 
        lambda d: getattr(op,ineq_1)(float(d[val1]), wert1) 
                  or getattr(op,ineq_2)(float(d[val2]), wert2), 
        L 
    ), 
} 
 
mapped_list = andor[select](cleaned_list) 
for x in mapped_list: 
    print(dict(x)) 

可能的选择是 gt(大于)、lt(小于)或 eq。


请注意,您甚至可以使用 python 内置模块 operator 的方法 and_ 和 or_ 使事情变得更加“动态”。 .例如,做

#Where the two following ix2-like stuffs are defined to make 
# a correspondence between names one knows, and methods of the 
#  module operator. 
ix2conj = { 
    1:'and_', 
    2:'or_', 
} 
ix2ineq = { 
    '<' :'lt', 
    '==':'eq', 
    '>' :'gt', 
} 
def my_filter(conjunction, inequality1, inequality2, my_cleaned_list): 
    return filter( 
        lambda d: getattr(op, ix2conj[conjunction])( 
                       getattr(op, ix2ineq[inequality1])(float(d[val1]), wert1), 
                       getattr(op, ix2ineq[inequality2])(float(d[val2]), wert2) 
                       ), 
        my_cleaned_list 
        ) 
 
ineq_1    = '>' 
ineq_2    = '<' 
select    = 2 
print(my_filter(select, ineq_1, ineq_2, cleaned_list))