Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

python中循环的随机值为什么是固定值?

titleList=[['a','b','c'],['1','2','3'],['x','y','z']]
word=[]
for i in range(10):
    for t in titleList:
        word.append(random.choice(t))
    title=''.join(word)
    print(title)

我希望组合出来的字符是随机的,为什么出来是一样的呢?
谢谢了,帮我找一下问题。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

因为你的word数组变量是全局的,你应该修改为局部变量

titleList=[['a','b','c'],['1','2','3'],['x','y','z']]

for i in range(10):
    word=[]
    for t in titleList:
        word.append(random.choice(t))
    title=''.join(word)
    print(title)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...