簡體   English   中英

將“設置” function 轉換為真/假

[英]transform "set" function to True/False

您好我想知道是否有可能知道在第一種情況下是否有多個重復項返回“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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM