将 "set" 函数转换为 True/False

transform "set" function to True/False

你好,我想知道是否有可能知道在第一种情况下是否有多个重复项 return “True”,如果不是在第二种情况下“False”?

例子:


import random

list = []
word = ""
a = 0

while a < 10 :
    for i in range(0,10):
        word = word + str(random.randint(0,9))
        i = i + 1
    list.append(word)
    word = "" #reset
    print(list)
    a = a + 1
# it's just an example it's not my real program
# and from that I would like to know if in my list
# there are duplicates by returning False or True.

如果我没理解错的话,你可以使用集合并将其长度与原始列表进行比较:

if len(set(yourList)) < len(yourList):
    return True
else:
    return False

如果您想测试重复项,请尝试类似的操作:

if len(my_list) != len(set(my_list):
    return "Your list contains duplicate values"
else:
    return "The values in your list are unique"

如果您只想测试列表中第一项没有重复项,请尝试使用 Counter

from collections import Counter

my_count = Counter(my_list)

if my_count[my_list[0]) > 1:
    return True
else:
    return False