【问题标题】:Python 'if' and 'while' conditions not workingPython 'if' 和 'while' 条件不起作用
【发布时间】:2017-10-26 13:36:18
【问题描述】:

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

这是我的输入文件:

1   2   3   10
7   9   100

这是用于调试的打印命令的相关代码:

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 条件读取为 true。

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 &lt; 7 不对!),而且在 while 循环中也失败了,因为 'i' 变为 4,即 list1 的大小。发生了什么事?!

【问题讨论】:

    标签: python if-statement while-loop conditional-statements


    【解决方案1】:

    你想要and,而不是or,在你的while循环测试中:

    while i < len(list1) and j < len(list2):
    
    如果其中一个测试为真

    (i &lt; len(list1)) or (j &lt; len(list2)) 将为真。因此,只要j 小于len(list2)i 就不会 小于len(list1)False or True 仍然是 True

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

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

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

    比较整数:

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

    但是,您可能希望在读取文件输入时将其转换为整数。

    【讨论】:

      猜你喜欢
      • 2013-07-06
      • 2020-07-15
      • 1970-01-01
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 2018-10-16
      • 2015-04-18
      相关资源
      最近更新 更多