Python';如果';和';而';不起作用的条件

Python';如果';和';而';不起作用的条件,python,if-statement,while-loop,conditional-statements,Python,If Statement,While Loop,Conditional Statements,我正在编写一个简单的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)) o

我正在编写一个简单的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
print'list1 len='+str(len(list1))+',list2 len='+str(len(list2))
而(i
程序读取正确的值,但似乎总是在每次迭代时将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
list1 len=4,list2 len=3
i=0
列表1[i]=1
1 < 7
i=1
列表1[i]=2
2 < 7
i=2
列表1[i]=3
3 < 7
i=3
清单1[i]=10
10 < 7
i=4
回溯(最近一次呼叫最后一次):
文件“q2.py”,第22行,在
打印'list1[i]='+str(list1[i])
索引器:列表索引超出范围

if语句不仅不起作用(
10<7
不正确!),而且在
while
循环中也失败了,因为
'i'
变为4,
list1
的大小。发生了什么事

您希望
,而不是
,在
while
循环测试中:

while i < len(list1) and j < len(list2):
在测试其他字符之前比较第一个字符,
'1'
'2'
之前排序

比较整数:

if int(list1[i]) < int(list2[j]):
if int(列表1[i])
但是,您可能希望在读取文件输入时将其转换为整数

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