2016-11-11 125 views
1

我需要檢查元組列表是否按元組的第一個屬性排序。最初,我想要根據它的排序自我來檢查這個列表。如...如何檢查兩個元組列表是否相同

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]不會成爲選項,因爲我不確定列表的長度。 謝謝

回答

7

我相信你可以做list1 == sortedlist1,而不必單獨查看每個元素。

+0

這是正確的,因爲類似類型的序列支持迭代字典對比。查看錶格[here]後面的註釋(https://docs.python.org/3.6/library/stdtypes.html#common-sequence-operations)。因此,等式比較會逐步迭代序列,直到遇到不同的對或序列的末尾(並且在前一種情況下返回「假」,而在後者中返回「假」)。 –

0

如果你想檢查是否列表進行排序或不是一個非常簡單的解決方案浮現在腦海:

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

@joce已經提供an excellent answer(我會建議接受一個,因爲它是更簡潔和直接回答你的問題),但我想,以解決您的原始信息的這一部分:

列表中可能有5個或可能是100,所以在進行,因爲我不知道名單有多長list1[0] == sortedlist1[0], and list1[1] == sortedlist1[1]不會是一個選項的長度。

如果要比較兩個列表中的每個元素,則不需要確切知道列表的長度。編程完全是懶惰的,所以你可以打賭,好的程序員會用手寫出許多比較結果!

相反,我們可以通過索引遍歷兩個列表。這將允許我們同時對兩個列表中的每個元素執行操作。這裏有一個例子:

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 
相關問題