【发布时间】: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 < 7 不对!),而且在 while 循环中也失败了,因为 'i' 变为 4,即 list1 的大小。发生了什么事?!
【问题讨论】:
标签: python if-statement while-loop conditional-statements