gpt4 book ai didi

python - 列表比较失败

转载 作者:太空宇宙 更新时间:2023-11-04 10:33:48 25 4
gpt4 key购买 nike

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

当 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)

最佳答案

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

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 中,直到创建副本为止。

关于python - 列表比较失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24764162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com