如何使用.join生成两个随机字符?

时间:2019-06-24 16:18:29

标签: python

我正在尝试让我的程序打印带有一个基数和两个随机数的序列

import random
import string

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"
y27Base = ["U0330V", "U0330W", "U0330X", "U0330Y"]

whatSerial = input("What serial?").upper()

def y27(y27Base, charList):
    return y27Base + "".join([random.choice(charList) for x in range(2)]) + " -> Y27"
if whatSerial == "Y27F":
    for i in y27Base:
        for i2 in charList:
            print(y27(i, i2))

我想要的是该程序以2个随机值打印y27Base,因此对于e.x

U0330V9D U0330XZ7

,我希望它打印尽可能多的

非常感谢

1 个答案:

答案 0 :(得分:1)

您的关键问题是您将单个字符传递给函数:

    for i2 in charList:
        print(y27(i, i2))

因此,您的函数只有一个字符可供选择,并且您会得到困扰输出的双字母。

要解决此问题,只需从主程序中传入字符列表即可:

for i in y27Base:
    print(y27(i, charList))

输出:

U0330VFG -> Y27
U0330WDC -> Y27
U0330XEM -> Y27
U0330YCI -> Y27

“越多越好”没有限制:您可以根据自己的喜好循环执行此内部语句。