Python でリストが等しいかどうかの判断に関する質問
この記事では、リストが等しいかどうかを判断する過程で遭遇する問題を主に記録し、リストが等しいかどうかを判断するための関連知識をまとめます。
目次
0. 問題の原因
この記事を書いた理由は、リストが等しいかどうかを判断する過程で ==、is、operator.eq() の 3 つのメソッドに疑問があるため、これら 3 つのメソッドを次のようにまとめます。
1. == 演算を使用して、リストが等しいかどうかを判断します
== 演算を使用してリストが等しいかどうかを判断するコードは次のとおりです。
# 1.使用 == 判断两个列表是否相同
a = [1, 2, 'apple']
b = [1, 2, 'apple']
c = ['apple', 1, 2]
result_a_b = (a == b)
print("result_a_b = {}".format(result_a_b))
print("type(result_a_b) is {}".format(type(result_a_b)))
print("The result of a == b is : {}".format(a == b))
print("The result of a == c is : {}".format(a == c))
print("The result of b == c is : {}".format(b == c))
print('\n')
操作の結果は次のようになります。
result_a_b = True
type(result_a_b) is <class 'bool'>
The result of a == b is : True
The result of a == c is : False
The result of b == c is : False
2. is 演算を使用して、リストが等しいかどうかを判断します
is 演算を使用してリストが等しいかどうかを判断するコードは次のとおりです。
# 2.使用 is 操作判断两个列表是否相等
a = [1, 2, 'apple']
b = [1, 2, 'apple']
c = ['apple', 1, 2]
d = a
print("The result of 'a is b' is : {}".format(a is b))
print("The result of 'a is c' is : {}".format(a is c))
print("The result of 'b is c' is : {}".format(b is c))
print("The result of 'a is d' is : {}".format(a is d)) # 因为列表d是列表a的简单赋值操作,所以是相等的
print('\n')
操作の結果は次のようになります。
The result of 'a is b' is : False
The result of 'a is c' is : False
The result of 'b is c' is : False
The result of 'a is d' is : True
代入、浅いコピー、および深いコピーの概念については、ブログ投稿「Python でのリスト list の代入」を参照してください。
3. リストが等しいかどうかを判断するには、operator.eq() を使用します。
Operator.eq() を使用してリストが等しいかどうかを判断するコードは次のとおりです。
# 3.使用operator.eq()操作判断两个列表是否相等
from operator import *
x = [1, 2, 'apple']
y = [1, 2, 'apple']
z = ['apple', 1, 2]
result_x_y = eq(x, y)
print("The type of result_x_y is : {}".format(type(result_x_y)))
print("The result of eq(x,y) is : {}".format(eq(x, y)))
print("The result of eq(x,z) is : {}".format(eq(x, z)))
print("The result of eq(y,z) is : {}".format(eq(y, z)))
print('\n')
操作の結果は次のようになります。
The type of result_x_y is : <class 'bool'>
The result of eq(x,y) is : True
The result of eq(x,z) is : False
The result of eq(y,z) is : False
4. まとめ
リストが等しいかどうかを判断するには、operator.eq()関数を直接使用する方法が最も直接的です。