在不知道它们的值的情况下检查 python 中的几个变量的不等式
Checking the inequality of several variables in python without knowing their value
我有四个字符串变量:a,b,c,d
。我不知道它们的值(它们是随机分配的),我不在乎。我只需要确保它们中的每一个都与其他变量不同,并且没有两个变量具有相同的值。我试过了
if a != b != c != d:
return true
但它不起作用。我该怎么办?
你可以使用天真的方法:
if a != b and a != c and a != d and b != c and b != d and c != d:
# do something
或者您可以利用集合不能两次保存相同的可哈希值这一事实:
if len(set([a, b, c, d])) == 4:
# do something
或者,更短的写法:
if len({a, b, c, d}) == 4:
# do something
您的代码不起作用的原因是因为您确实在这样做:
if a != b and b != c and c != d:
return true
因此,它只检查您需要检查的部分内容,它检查紧接在彼此后面的所有值是否相等,但不检查相隔多于一个位置的值是否相等。
这样做吗?
assert len({a, b, c, d}) == 4 # set of 4 distinct elements should be 4
if len({a, b, c, d}) == 4:
return True
你的条件不工作的原因
>>> 1 != 2 != 1
True
从上面的例子中,1 != 2
和2 != 1
,因此通过了条件。它不会检查您的第一个和第三个变量是否相等。
你不能像这样链接比较。下面是使用 if 语句的一种方法,尽管它很混乱。
if (a != b and a != c and a != d
and b != c and b != d and c !=d):
return True
一个绝妙的方法(尽管速度和 space 成本稍低)如下:
things_to_see_if_unique = [a, b, c, d]
if len(things_to_see_if_unique) == len(set(things_to_see_if_unique)):
return True
我有四个字符串变量:a,b,c,d
。我不知道它们的值(它们是随机分配的),我不在乎。我只需要确保它们中的每一个都与其他变量不同,并且没有两个变量具有相同的值。我试过了
if a != b != c != d:
return true
但它不起作用。我该怎么办?
你可以使用天真的方法:
if a != b and a != c and a != d and b != c and b != d and c != d:
# do something
或者您可以利用集合不能两次保存相同的可哈希值这一事实:
if len(set([a, b, c, d])) == 4:
# do something
或者,更短的写法:
if len({a, b, c, d}) == 4:
# do something
您的代码不起作用的原因是因为您确实在这样做:
if a != b and b != c and c != d:
return true
因此,它只检查您需要检查的部分内容,它检查紧接在彼此后面的所有值是否相等,但不检查相隔多于一个位置的值是否相等。
这样做吗?
assert len({a, b, c, d}) == 4 # set of 4 distinct elements should be 4
if len({a, b, c, d}) == 4:
return True
你的条件不工作的原因
>>> 1 != 2 != 1
True
从上面的例子中,1 != 2
和2 != 1
,因此通过了条件。它不会检查您的第一个和第三个变量是否相等。
你不能像这样链接比较。下面是使用 if 语句的一种方法,尽管它很混乱。
if (a != b and a != c and a != d
and b != c and b != d and c !=d):
return True
一个绝妙的方法(尽管速度和 space 成本稍低)如下:
things_to_see_if_unique = [a, b, c, d]
if len(things_to_see_if_unique) == len(set(things_to_see_if_unique)):
return True