如何确保17个变量中的数字不同? - python

我有17个变量(S1,S2 ... S17),我需要检查它们是否都不同。除此以外,还有其他方法吗

if S1 != S2 and S1!=S3...

因为我真的不想写136条语句。列表的某种方法,也许吗?

python大神给出的解决方案

如果所有这些数据都是可哈希的,则只需构造一个集合并检查其长度即可,如下所示

if len({s1, s2, s3..., s17}) == 17:
   # All are not equal

例如,如果它们都是整数,例如you mentioned in the comments,

>>> s1, s2, s3 = 1, 1, 1
>>> len({s1, s2, s3})
1
>>> s1, s2, s3 = 1, 2, 3
>>> len({s1, s2, s3})
3

如果所有数字都相同,则set将只有1个元素,因为所有重复项都将被删除。因此,要检查所有元素是否都不同,只需将集合的长度与变量总数进行比较。

相反,您可以像这样直接写条件

if not (s1 == s2 == s3 == .... s17):
   # All are not equal

在内部,Python会像这样执行它

if not ((s1 == s2) and (s2 == s3) and (s3 == s4) ... and (s16 == s17)):
   # All are not equal