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
125 views
in Technique[技术] by (71.8m points)

python - Add random values to multiple lists

import string
import random
    
string_pool = ["W", "X", "Y", "Z"]
names = ["Ironman", "Thor", "Spiderman"]

def func1(a):
    d = []
    for b in a:
        continue
    for c in range(5):
        c += 1
        d += random.choice(string_pool)
    return print("{} : ".format(b) , d)

func1(names)

I expect the result of this code is below

Ironman : ["X", "X", "Y", "Z", "X"]
Thor : ["Y", "X", "Z", "Z", "X"]
Spiderman : ["Y", "Y", "Y", "Z", "X"]

but, the result is

Spiderman : ["Y", "Y", "Y", "Z", "X"]

only spiderman... what should i change in my code? Thank you!

question from:https://stackoverflow.com/questions/65896429/add-random-values-to-multiple-lists

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

1 Answer

0 votes
by (71.8m points)
for b in a:
        continue

Not sure what you expect this line to do.

What it actually does is execute a for loop in which nothing happens. At the beginning of each iteration of a for loop, the loop control variable (in this case b) gets assigned the value of the next element in the iterable (in this case, a.

In this case, the loop would iterate three times:

b = 'Ironman'
b = 'Thor'
b = 'Spiderman'

and since the interior of the loop is empty (just the continue statement, which means "jump back to the top of the loop immediately and go to the next iteration"), nothing happens.

Now, once the loop finishes iterating, the variable b isn't cleared or reset. The last thing assigned to it was the last element of a, which is the string 'spiderman'.


Did you mean to do:

for b in a:
    d = []
    for c in range(5):
        d += random.choice(string_pool)
    print("{} : ".format(b) , d)

Note how the rest of the function is inside the for loop.


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

...