Python重复元素判定

【提示】输入列表元素时,各元素之间使用逗号分隔。如果列表只包含一个元素,末尾要写一个逗号。由于输入多个使用逗号隔开的数值元素时,默认返回类型为元组,因此可以通过list将元组转换为列表。例如:

 ls = list(eval(input("Input list(separate with comma):")))

【输入输出示例1】

Input list(separate with comma):4,5,8,3,4

No

【输入输出示例2】

Input list(separate with comma):1,2,3,4,5,6,7

Yes

只要判断列表转集合后,元素个数是否相等即可。 因为集合的元素是有唯一性的,所以一转就相当于去重了。

ls = list(eval(input("Input list(separate with comma):")))

if len(ls)==len(set(ls)):
    print('Yes')
else:
    print('No')

ls = list(eval(input("Input list(separate with comma):")))
if len(ls)==len(set(ls)):
    print("Yes")
else:
    print("No")

img

img

代码如下:

ls = list(eval(input("Input list(separate with comma):")))
_dict = {}
flag = 1
for i in ls:
    if i in _dict.keys():
        print("No")
        flag = 0
        break
if flag:
    print("Yes")

上述测试一二已通过


如有问题及时沟通


ls = list(eval(input("Input list(separate with comma):")))
len = len(ls)
count = 0
for i in range(len - 1):
    for j in range(0,len - i - 1):
        if ls[j] > ls[j + 1]:
            temp = ls[j]
            ls[j]=ls[j+1]
            ls[j+1]=temp
for i in range(len - 1):
    for j in range(0,len - i - 1):
        if ls[j] == ls[j + 1]:
            count = count + 1
if count == 0:
    print("Yes")
else:
    print("N0")

set: Build an unordered collection of unique elements. # 去重

len(list) 对比 len(set(list)) 长度