如何从列表中调用比较运算符

时间:2019-01-26 15:11:13

标签: python list comparison operators

您好,我想安装某种可调比较器,其中比较列表 a 中的元素和列表 Values 中的元素,并使用从中读取的运算符列表操作员

a = [1,2,3,4] # This should be variable
Val = [0.5,1,10,7] # This should have the same length as a
Op = ['<','>','<>','<']

for i in range(len(a)):
    print(a[i]Op[i]Val[i])

4 个答案:

答案 0 :(得分:4)

使用operators中的函数代替比较符号。

这可能会有所帮助!

from operator import lt, gt, ne, le,eq
a = [1,2,3,4] # This should be variable
val = [0.5,1,10,7] # This should have the same length as a
operation = {'<': lt, '>': gt, '<>': ne, '=': eq}


op = ['<','>','<>','<']

for i,o,j in zip(a,op,val):
    print(operation[o](i,j))

False
True
True
True

答案 1 :(得分:1)

似乎您需要编程的方式来调用比较运算符,operator模块将完成此工作。构造运算符功能列表或通过dict

标记运算符映射

答案 2 :(得分:1)

即使在某些情况下也使用eval是不稳定的,但是如果仅考虑您的情况,它可以按预期工作,并且sympy

是一个更好的解决方案
a = [1,2,3,4] # This should be variable
Val = [0.5,1,10,7] # This should have the same length as a
Op = ['<','>','!=','<']

for i in range(len(a)):
    parse_expr(str(a[i])+Op[i]+str(Val[i]))# or change to eval(str(a[i])+Op[i]+str(Val[i]))

False
True
True
True

答案 3 :(得分:0)

a = [1,2,3,4] # This should be variable
b = [0.5,1,10,7] # This should have the same length as a
c = ['<','>','<>','<']

使用

for i in range(len(a)):
    eval(str(a[i])+b[i]+str(c[i]))