2016-11-11 4 views
1

タプルのリストがタプルの最初の属性によってソートされているかどうかを確認する必要があります。最初は、ソートされた自己に対してこのリストをチェックしようとしました。 ...タプルの2つのリストが同一かどうかを確認する方法

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

これは、同じタイプのシーケンスが反復的な辞書編集上の比較をサポートするので、正しいです。表の後ろの注記を参照してください(https://docs.python.org/3.6/library/stdtypes.html#common-sequence-operations)。したがって、等価比較は、シーケンスの異なるペアまたはシーケンスの終わり(前者の場合は「False」、後者の場合は「True」を返す)まで、シーケンス内のシーケンスを反復します。 –

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 

これは一度だけあなたのリストの上に行くの付加的な利点を有しています。それを並べ替えて比較すると、少なくとも1回以上リストを上回ります。

あなたはまだそのようにやりたい場合は、ここでは別の方法です:

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を提供する(と私はそれがより簡潔であり、1として直接あなたの質問に答えることを受け入れることを示唆しています)、私はあなたのオリジナルのポストのこの部分に対処したい:

リストは5または多分100の長さを有することができるので、私はリストがどのくらいかわからないので、list1[0] == sortedlist1[0], and list1[1] == sortedlist1[1]を実施することはオプションではありません。

2つのリストのすべての要素を比較する場合は、リストの正確な長さを知る必要はありません。プログラミングはすべて怠け者だから、良いプログラマが手で多くの比較を書いてくれることはないだろう!

代わりに、インデックスで両方のリストを繰り返し処理できます。これにより、2つのリストの各要素に対して同時に操作を実行することができます。

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 
関連する問題