测试元组是否具有所有不同的元素 [英] Testing whether a tuple has all distinct elements

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

问题描述

我一直在寻找一种测试元组是否具有所有不同元素的方法-可以说,它是一个集合,最终得到了这种快速而肮脏的解决方案。

I was seeking for a way to test whether a tuple has all distinct elements - so to say, it is a set and ended up with this quick and dirty solution.

def distinct ( tup):
    n=0
    for t in tup:
        for k in tup:
            #print t,k,n
            if (t == k ):
                n = n+1
    if ( n != len(tup)):
        return False
    else :
        return True


print distinct((1,3,2,10))

print distinct((3,3,4,2,7))

是否有思维错误?元组上有内置函数吗?

Any thinking error? Is there a builtin on tuples?

推荐答案

您可以很容易地做到:

len(set(tup))==len(tup)

这将创建 tup ,并检查其长度是否与原始的 tup相同。它们唯一具有相同长度的情况是 tup 中的所有元素都是唯一的

This creates a set of tup and checks if it is the same length as the original tup. The only case in which they would have the same length is if all elements in tup were unique

>>> a = (1,2,3)
>>> print len(set(a))==len(a)
True

>>> b = (1,2,2)
>>> print len(set(b))==len(b)
False

>>> c = (1,2,3,4,5,6,7,8,5)
>>> print len(set(c))==len(c)
False

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

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