测试所有N个变量是否都不同 [英] Test if all N variables are different

查看:56
本文介绍了测试所有N个变量是否都不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创造一个条件,其中所有选定变量都不相等.到目前为止,我的解决方案是比较每对扩展不佳的对:

I want to make a condition where all selected variables are not equal. My solution so far is to compare every pair which doesn't scale well:

if A!=B and A!=C and B!=C:

我想对多个变量(例如五个或更多)进行相同的检查,这让很多变量感到困惑.我可以做些什么来简化它?

I want to do the same check for multiple variables, say five or more, and it gets quite confusing with that many. What can I do to make it simpler?

推荐答案

创建一个集合,并检查集合中的元素数是否与传递给它的列表中的变量数相同:

Create a set and check whether the number of elements in the set is the same as the number of variables in the list that you passed into it:

>>> variables = [a, b, c, d, e]
>>> if len(set(variables)) == len(variables):
...     print("All variables are different")

一个集合没有重复的元素,因此,如果您创建一个集合并且它具有与原始列表中的元素数量相同的元素数量,那么您就会知道所有元素彼此都不相同.

A set doesn't have duplicate elements so if you create a set and it has the same number of elements as the number of elements in the original list then you know all elements are different from each other.

这篇关于测试所有N个变量是否都不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆