打印时检查重复项

时间:2019-06-10 14:30:21

标签: python

我正在使用random和base生成序列。 (请参见下面的示例)

import random

charList = ["A", "B", "C", "D", "C", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5"
"6", "7", "8", "9"]

def Z150(charList):
    return "1841GG001Z" + random.choice(charList) + "8" + " -> Z150 Speakerset"
for i in range(100):
    print(Z150(charList))

现在,很可能会有重复项,我如何找到重复项并将其删除?

我已经看到了执行此操作的方法,但是没有任何方法可以检查打印输出,然后删除重复的打印件(如果这样的话)

2 个答案:

答案 0 :(得分:1)

使用基本python的一种方法是列出已生成的内容,然后跳过它:

printed = set()
for i in range(100):
    z150 = Z150(charList)
    if not z150 in printed:
        printed.add(z150)
        print(z150)

或者您也可以使用单线,然后首先获得一套,然后再打印:

snums = set(Z150(charList) for _ in range(100))
for s in snums: 
    print(s)

答案 1 :(得分:0)

使用字符串模块并随机播放

import random
import string

charList=list(string.ascii_uppercase+string.digits[1:])


def Z150(i):
    return  "1841GG001Z" + i + "8" + " -> Z150 Speakerset"
random.shuffle(charList)        
for i in charList[:20]:
    print(Z150(i))