@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}$