列表比较失败

时间:2014-07-15 17:08:48

标签: python list compare

出于某种原因,我让列表始终相等,即使在打印时,您也可以看到它们并不总是相等。

当previous_list = [1,0,0,0,0]和current_list = [0,0,0,0,0]

时,它返回True

关于比较列表有很多问题,但是我尝试了许多不同的答案,比如cmp(),但它也返回0。那么为什么说它一样,但是在打印时,你会发现它们是不同的?

while True:
    previous_status_list = current_status_list
    print str(previous_status_list) + " PREVIOUS"
    if door_status == 'closed' and status_for_loop == 'closed':
        overall_status_list[0] = 0
    else:
        overall_status_list[0] = 1
    if door_locked_status == False:
        overall_status_list[1] = 0
    else:
        overall_status_list[1] = 1
    if door_breached_status == False:
        overall_status_list[2] = 0
    else:
        overall_status_list[2] = 1
    if door_propped_status == False:
        overall_status_list[3] = 0
    else:
        overall_status_list[3] = 1
    if egress_status == False:
        overall_status_list[4] = 0
    else:
        overall_status_list[4] = 1
    current_status_list = overall_status_list
    if current_status_list == previous_status_list:
        print 'TRUE'
    else:
        print 'False'
    print str(current_status_list)  + " CURRENT"
    sleeptime.sleep(3)

1 个答案:

答案 0 :(得分:4)

您没有比较两个不同的列表,因为您没有复制:

previous_status_list = current_status_list

previous_status_listcurrent_status_list引用相同的对象。通过一个引用更改列表会改变另一个引用:

创建一个(浅)副本:

previous_status_list = current_status_list[:]

演示:

>>> current_status_list = ['foo', 'bar', 'baz']
>>> previous_status_list = current_status_list
>>> current_status_list is previous_status_list
True
>>> current_status_list.append('spam')
>>> previous_status_list
['foo', 'bar', 'baz', 'spam']
>>> previous_status_list = current_status_list[:]  # shallow copy
>>> current_status_list is previous_status_list
False
>>> current_status_list.append('ham')
>>> current_status_list
['foo', 'bar', 'baz', 'spam', 'ham']
>>> previous_status_list
['foo', 'bar', 'baz', 'spam']

注意is标识运算符如何显示两个名称引用同一对象,直到创建副本。此外,通过current_status_list对列表的更改会显示在previous_status_list中,直到创建副本为止。