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

Python 如何确保17个变量中的数字不同?,python,if-statement,comparison,Python,If Statement,Comparison,我有17个变量(S1,S2…S17),我需要检查它们是否都不同。除此之外还有别的办法吗 if S1 != S2 and S1!=S3... 因为我真的不想写136条语句。列表的某种方法,也许?如果所有这些数据都是可散列的,您只需构造一个集合并检查其长度,如下所示 if len({s1, s2, s3..., s17}) == 17: # All are not equal if not (s1 == s2 == s3 == .... s17): # All are not equ

我有17个变量(S1,S2…S17),我需要检查它们是否都不同。除此之外还有别的办法吗

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

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

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

if len({s1, s2, s3..., s17}) == 17:
   # All are not equal
if not (s1 == s2 == s3 == .... s17):
   # All are not equal
if not ((s1 == s2) and (s2 == s3) and (s3 == s4) ... and (s16 == s17)):
   # All are not equal
例如,如果它们都是整数

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


相反,您可以直接编写条件,如下所示

if len({s1, s2, s3..., s17}) == 17:
   # All are not equal
if not (s1 == s2 == s3 == .... s17):
   # All are not equal
if not ((s1 == s2) and (s2 == s3) and (s3 == s4) ... and (s16 == s17)):
   # All are not equal
在内部,Python将这样执行它

if len({s1, s2, s3..., s17}) == 17:
   # All are not equal
if not (s1 == s2 == s3 == .... s17):
   # All are not equal
if not ((s1 == s2) and (s2 == s3) and (s3 == s4) ... and (s16 == s17)):
   # All are not equal
您也可以使用
any()


也许你可以把所有的变量放在一个列表中。当您将其转换为一个集合,并且该集合的长度仍然为17时,所有变量都是唯一的。如果存在重复值,则新创建的集合将小于17。因此,您可以将存储有变量的列表转换为一个集合,并检查列表和集合的长度是否相同。

这些变量的类型是什么?@thefourtheye,只需整数谢谢,正是我需要的!如果
s1==s2==…s17
耗时?@itzmeontv这是另一种直接的方法。我只是加入并解释了它是如何工作的。谢谢:-)@itzmeontv我不明白:
s1==s2==…s17
AFAICT这将测试所有值是否相同。和
s1=s2!=。。。s17
将假定重复值是连续值。它们都不适用于OP用例——或者我遗漏了什么?(
1!=2!=1
True
2!=1!=1
)@SylvainLeroux哦。。。谢谢你指出这一点。我现在修好了。