更快地检查成员资格多个值的列表

时间:2017-08-22 12:58:04

标签: python-2.7

我想测试多个值是否在列表中具有成员资格,但脚本非常慢。 到目前为止我尝试了什么:

list1 = [10,20,35,45,67,88,99]

for x in list1:
    if 9<x<11:
        for x in list1:
            if 34<x<39:
                for x in list1:
                    if 87<x<90:
                        print "YEAH"

1 个答案:

答案 0 :(得分:0)

一般的想法是在满足所有条件后完成迭代。

可能有更聪明的方法来解决它,但我能想到的最简单的方法是跟踪所有条件的结果,并在它们全部为True后立即中断。例如:

list = [10, 20, 35, 45, 67, 88, 99, 0]
// there we will keep track of each test
cond1 = False
cond2 = False
cond3 = False

// Each of the conds will become True and will keep that value.
for x in list:
  cond1 = cond1 or (9 < x < 11)
  cond2 = cond2 or (34 < x < 39)
  cond3 = cond3 or (87 < x < 90)

  if cond1 and cond2 and cond3:
  // once all of them become True, we know what we want and can break the loop
    print "YEAH"
    break