python-3.xfor-loopzipoutputassociate

How to combine for loop output with another for loop output?


Let's say I have a loop that generates random names

names = ['Kiri', 'Elizabeth', 'Philip', 'Charlotte', 'Lydia']

random_names = []
for x in range(3):
    random_names.append(random.choice(names))
print (random_names)

-This would print out random 3 names e.g ['Charlotte', 'Lydia', 'Kiri']

Then I want to generate random numbers, lets say from 1 to 20

random_numbers = random.sample([x for x in range (1,20)], (3))
print (random_numbers)

And lets say we got [7, 13, 2]

Then my question is, I want to assign these random numbers to following random names so that it is associated with the name. How should I write the code in a way so it can appear as

('Charlotte', 7), ('Lydia', 13), ('Kiri', 2)

Thanks in advance !


Solution

  • There are several way for doing it you can use zip look this little example:

    names = ['Kiri', 'Elizabeth', 'Philip', 'Charlotte', 'Lydia']
    random_numbers = random.sample([x for x in range (1,20)], (3))
    zip(names,random_numbers)
    

    output

    [('Kiri', 19), ('Elizabeth', 3), ('Philip', 1)]

    The output above is a list of tuples