Python的“ if”和“ while”条件不起作用 [英] Python 'if' and 'while' conditions not working

查看:161
本文介绍了Python的“ if”和“ while”条件不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的Python程序。应该从制表符描述的文件中读取两个已排序列表,然后将它们合并为一个已排序列表。算法虽然不太严格,但是Python似乎忽略了循环和if语句中的条件!

I am writing a simple Python program. It's supposed to read two sorted lists from tab-delineated file and merge them into a single sorted list. The algorithm isn't too tough but Python seems to be ignoring the conditions in my loops and if statements!

这是我的输入文件:

1   2   3   10
7   9   100

以下是打印命令的相关代码,用于调试:

Here's the relevant bit of code with print commands for debugging:

print 'list1 len =' + str(len(list1)) + ', list2 len = ' + str(len(list2))
while (i < len(list1)) or (j < len(list2)):
    print 'i = ' + str(i)
    print 'list1[i] = ' + str(list1[i])
    if (list1[i] < list2[j]):
        print str(list1[i]) + ' < ' + str(list2[j])
        output.append(list1[i])
        i += 1
    else:
        output.append(list2[j])
        j += 1

程序读取正确的值,但似乎总是读取if条件

The program reads in the correct values but seems to always read the if-condition as true at every iteration.

list1 len =4, list2 len = 3
i = 0
list1[i] = 1
1 < 7
i = 1
list1[i] = 2
2 < 7
i = 2
list1[i] = 3
3 < 7
i = 3
list1[i] = 10
10 < 7
i = 4
Traceback (most recent call last):
  File "q2.py", line 22, in <module>
     print 'list1[i] = ' + str(list1[i])
IndexError: list index out of range

if语句不仅不起作用( 10< 7 是不正确的!),而且在 while 循环,因为'i'变为4,即 list1

Not only is the if-statement not working (10 < 7 isn't right!), it's also failing at the while loop, since 'i' gets to 4, the size of list1. What is happening?!

推荐答案

您要,而不是,在您的 while 循环测试中:

You want and, not or, in your while loop test:

while i < len(list1) and j < len(list2):

(i 将是真的,如果其中一个测试是真的。因此 i 不会小于 len(list1) j 小于 len(list2) False或True 仍然是 True

(i < len(list1)) or (j < len(list2)) is going to be true if one of those tests is true. So i doesn't have to be smaller than len(list1) as long as j is smaller than len(list2). False or True is still True.

下一步,您的 if 测试很有可能是比较字符串,而不是整数。字符串按字典顺序进行比较:

Next, your if test is most likely comparing strings, not integers. Strings are compared lexicographically:

>>> 'abc' < 'abd'
True
>>> 'ab' < 'b'
True
>>> '10' < '2'
True

在测试其他字符之前先比较第一个字符,然后'1''2'之前排序。

The first characters are compared before other characters are tested, and '1' sorts before '2'.

比较而不是整数:

if int(list1[i]) < int(list2[j]):

您可能希望在输入文件时将文件输入转换为整数但是,请阅读它们。

You probably want to convert your file inputs to integers the moment you read them, however.

这篇关于Python的“ if”和“ while”条件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆