我有以下两个清单:
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
之一}
答案 0 :(得分: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
。
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))
答案 1 :(得分:0)
我看到你的语法来自哪里,但这不是python中的“和”和“或”关键字所做的。为了做你想要的,我想你会想要使用内置类型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