如果条件表达不起作用

ely*_*yon 2 python if-statement

我有两个列表,其中包含以下值

List1=['6', '9', '16', '19', '0', '3', '6', '0', '6', '12', '18']

List2=['9', '16', '19', '24', '3', '6', '19', '6', '12', '18', '24']
Run Code Online (Sandbox Code Playgroud)

下面是我的python代码的循环,当idk为60时,if条件不起作用,时间= 60/60 = 1k

在这种情况下,当list1k为'0'且列表2为'3'时,它应该进入if条件.但是if条件不起作用.我也尝试使用以下表达式:

if ((time >=List1[i]) and (time <=List2[i])):
Run Code Online (Sandbox Code Playgroud)

这是代码:

for id in range(60,63):
    time = id/ 60
    for i in range(0, len(List1) - 1):
    if (((time >List1[i])or(time==List1[i])) and ((time <List2[i])or(time==List2[i]))):
        print "inside IF"
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 8

您正在比较字符串和整数.数字总是在字符串之前排序,因此time总是低于两者List1[i]List2[i].

改为在列表中使用整数:

List1 = [6, 9, 16, 19, 0, 3, 6, 0, 6, 12, 18]
List2 = [9, 16, 19, 24, 3, 6, 19, 6, 12, 18, 24]
Run Code Online (Sandbox Code Playgroud)

Python 2尝试使所有东西都可以订购,这就是为什么比较字符串和整数是合法的,但这也意味着你可以犯这样的错误.Python 3删除了这个目标,并试图将字符串与这样的整数进行比较,而不是引发错误.

请注意,您还使用整数除法,因为/除法运算符的两个操作数都是整数.您可能希望使用浮点除法:

time = id / 60.0
Run Code Online (Sandbox Code Playgroud)

虽然我不完全确定你对该部门的期望是什么.用整数除法得到的结果60 / 60,61 / 60并且62 / 60总是如此1.

if比较链可以简化您的表达式:

if List1[i] <= time <= List2[i]:
Run Code Online (Sandbox Code Playgroud)

您可以使用该zip()函数配对两个列表中的值:

for id in range(60, 63):
    time = id / 60.0
    for lower, higher in zip(List1, List2):
        if lower <= time <= higher:
            print 'inside if with lower={}, higher={}, time={}'.format(lower, higher, time)
Run Code Online (Sandbox Code Playgroud)

这输出:

>>> List1 = [6, 9, 16, 19, 0, 3, 6, 0, 6, 12, 18]
>>> List2 = [9, 16, 19, 24, 3, 6, 19, 6, 12, 18, 24]
>>> for id in range(60, 63):
...     time = id / 60.0
...     for lower, higher in zip(List1, List2):
...         if lower <= time <= higher:
...             print 'inside if with lower={}, higher={}, time={}'.format(lower, higher, time)
... 
inside if with lower=0, higher=3, time=1.0
inside if with lower=0, higher=6, time=1.0
inside if with lower=0, higher=3, time=1.01666666667
inside if with lower=0, higher=6, time=1.01666666667
inside if with lower=0, higher=3, time=1.03333333333
inside if with lower=0, higher=6, time=1.03333333333
Run Code Online (Sandbox Code Playgroud)

  • 使用Python 3修复的设计错误 (2认同)