Luc*_*uca 3 python arrays tuples list python-3.x
我有一个 3 元素元组,其中一个元素与其他两个元素不同。例如,它可能是这样的:(0.456, 0.768, 0.456)。
找到这个不同元素的索引的最简单方法是什么?我认为的一种方法考虑指数(0, 1)及(1, 2)这些,一会是不一样的。如果是,(0, 1)则将它们的元素与元素进行2比较,否则,将元素(1, 2)与索引0进行比较以找到不同的元素。
感觉就像我缺少一种pythonic方法来做到这一点。
一个简单的方法:
def func(arr):
x, y, z = arr
return 2 * (x == y) + (x == z)
Run Code Online (Sandbox Code Playgroud)
测试:
func(['B', 'A', 'A'])
# 0
func(['A', 'B', 'A'])
# 1
func(['A', 'A', 'B'])
# 2
Run Code Online (Sandbox Code Playgroud)