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

2024-04-24 23:03:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下两个清单:

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=";")]

我现在想从wert1wert2以及wert1wert2进行筛选。这意味着在and子句上,它应该在两个过滤器上true,在or子句上,它应该是wert1wert2True之一


Tags: andin列表forifselectfilteredlist
2条回答

您希望筛选包含在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内置模块^{}的方法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))

我知道你的语法是从哪里来的,但这根本不是python中的“and”和“or”关键字所做的。要实现您想要的功能,我想您应该使用内置类型set。你可以这样做

# note that this is already the "or" one
both = list1 + [x for x in list2 if not x in list1]

# for "and"
mapped_list = [x for x in both if x in list1 and x in list2]

如果希望结果列表只有唯一的值,则可以对

both = list1 + list2

相关问题 更多 >