python中while和if能混用那_Python的“ if”和“ while”条件不起作用

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!

Here's my input file:

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

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

print 'list1[i] = ' + str(list1[i])

IndexError: list index out of range

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?!

解决方案

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

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

(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.

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

>>> 'abc' < 'abd'

True

>>> 'ab' < 'b'

True

>>> '10' < '2'

True

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

Compare integers instead:

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值