python 唯一元素_检查所有元素在Python中是否唯一

python 唯一元素

Here, we are implementing a python program to check whether all elements of a list are unique or not?

在这里,我们正在实现一个python程序来检查列表的所有元素是否唯一?

It's very simple to check, by following two steps

按照以下两个步骤进行检查非常简单

  1. Convert the list in a set (as you should know that set contains the unique elements) – it will remove the duplicate elements if any.

    转换列表中的列表(您应该知道该集合包含唯一元素)–它将删除重复的元素(如果有)。

  2. Then, compare the length of the list and set – if both are the same then all elements are unique.

    然后,比较列表和集合的长度–如果两者相同,则所有元素都是唯一的。

Program:

程序:

# function to check unique
def check_unique(x):
  return len(x) == len(set(x))

# lists
x = [10, 20, 30, 40,50]
y = [10, 20, 20, 20, 20]
z = [10, 10, 10, 10, 10]

print("x: ", x)
print("len(x): ", len(x))
print("set(x): ", set(x))
print("len(set(x)): ", len(set(x)))
print("check_unique(x): ", check_unique(x))
print()

print("y: ", y)
print("len(y): ", len(y))
print("set(y): ", set(y))
print("len(set(y)): ", len(set(y)))
print("check_unique(y): ", check_unique(y))
print()

print("z: ", z)
print("len(z): ", len(z))
print("set(z): ", set(z))
print("len(set(z)): ", len(set(z)))
print("check_unique(z): ", check_unique(z))
print()

Output

输出量

x:  [10, 20, 30, 40, 50]
len(x):  5
set(x):  {40, 10, 50, 20, 30}
len(set(x)):  5
check_unique(x):  True

y:  [10, 20, 20, 20, 20]
len(y):  5
set(y):  {10, 20}
len(set(y)):  2
check_unique(y):  False

z:  [10, 10, 10, 10, 10]
len(z):  5
set(z):  {10}
len(set(z)):  1
check_unique(z):  False


翻译自: https://www.includehelp.com/python/check-all-elements-are-unique-or-not.aspx

python 唯一元素

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值