[英]How to check if two lists of tuples are identical
我需要檢查元組列表是否按元組的第一個屬性排序。 最初,我想根據它的排序自我檢查這個列表。 比如……
list1 = [(1, 2), (4, 6), (3, 10)]
sortedlist1 = sorted(list1, reverse=True)
然后我如何檢查 list1 是否與 sortedlist1 相同? 相同,如list1[0] == sortedlist1[0], and list1[1] == sortedlist1[1]
。
該列表的長度可能為 5 或 100,因此執行list1[0] == sortedlist1[0], and list1[1] == sortedlist1[1]
將不是一個選項,因為我不確定名單是。 謝謝
我相信你可以只做list1 == sortedlist1
,而不必單獨查看每個元素。
@joce 已經提供了一個很好的答案(我建議接受它,因為它更簡潔並且直接回答了您的問題),但我想解決您原始帖子的這一部分:
該列表的長度可能為 5 或 100,因此執行
list1[0] == sortedlist1[0], and list1[1] == sortedlist1[1]
將不是一個選項,因為我不確定名單是。
如果要比較兩個列表的每個元素,則無需確切知道列表的長度。 編程就是偷懶,所以你可以打賭,沒有一個好的程序員會手工寫出這么多的比較!
相反,我們可以使用index遍歷兩個列表。 這將允許我們同時對兩個列表的每個元素執行操作。 下面是一個例子:
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 是否通過質量運算符==
內置了此功能是一件很常見的事情。 因此,簡單地編寫要容易得多:
list1 == list2
如果您想檢查列表是否已排序,我會想到一個非常簡單的解決方案:
last_elem, is_sorted = None, True
for elem in mylist:
if last_elem is not None:
if elem[0] < last_elem[0]:
is_sorted = False
break
last_elem = elem
這有一個額外的好處,就是只檢查你的列表一次。 如果您對它進行排序然后比較它,那么您至少要查看列表不止一次。
如果您仍然想這樣做,這是另一種方法:
list1 = [(1, 2), (4, 6), (3, 10)]
sortedlist1 = sorted(list1, reverse=True)
all_equal = all(i[0] == j[0] for i, j in zip(list1, sortedlist1))
在python 3.x
,您可以使用eq
運算符檢查兩個元組a
和b
列表是否相等
import operator
a = [(1,2),(3,4)]
b = [(3,4),(1,2)]
# convert both lists to sets before calling the eq function
print(operator.eq(set(a),set(b))) #True
使用這個:
sorted(list1) == sorted(list2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.