python判断两个列表是否相同_如何检查两个元组列表是否相同

@joce已经提供了an excellent answer(我建议接受这一条,因为它更简洁、更直接地回答了您的问题),但我想在您最初的帖子中提到这一部分:The list may have a length of 5 or possibly 100, so carrying out list1[0] == sortedlist1[0], and list1[1] == sortedlist1[1] would not be an option because I am not sure how long the list is.

如果要比较两个列表中的每个元素,则不需要确切知道列表的长度。编程是关于懒惰的,所以你可以打赌没有一个好的程序员会手写出这么多的比较!在

相反,我们可以用索引遍历这两个列表。这将允许我们同时对两个列表中的每个元素执行操作。下面是一个例子:def compare_lists(list1, list2):

# Let's initialize our index to the first element

# in any list: element #0.

i = 0

# And now we walk through the lists. We have to be

# careful that we do not walk outside the lists,

# though...

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

if list1[i] != list2[i]:

# If any two elements are not equal, say so.

return False

# We made it all the way through at least one list.

# However, they may have been different lengths. We

# should check that the index is at the end of both

# lists.

if i != (len(list1) - 1) or i != (len(list2) - 2):

# The index is not at the end of one of the lists.

return False

# At this point we know two things:

# 1. Each element we compared was equal.

# 2. The index is at the end of both lists.

# Therefore, we compared every element of both lists

# and they were equal. So we can safely say the lists

# are in fact equal.

return True

也就是说,检查Python是否通过quality操作符==内置了此功能,这是一件非常常见的事情。因此,简单地写:

^{pr2}$

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值