简体   繁体   中英

Python, how to randomly add/append elements from one list to another?

import random
global colours 
global current
colours = ["Red","Yellow","Blue","Green","Orange","White"]
current = []

def randompicker():
    for i in range(4):
        current = random.choice(colours)
randompicker()
print(colours)
print(current)

Hey, so the above program is supposed to randomly add 4 of the elements from the list called colours into the other list named current. I have looked through the forums, but I cannot find help specific to this case.

In short, Is there a quick and efficient way to add 4 random elements from one list straight into another?

Thanks

You're describing the basic usage of random.sample .

>>> colours = ["Red","Yellow","Blue","Green","Orange","White"]
>>> random.sample(colours, 4)
['Red', 'Blue', 'Yellow', 'Orange']

If you want to allow duplicates, use random.choices instead (new in Python 3.6).

>>> random.choices(colours, k=4)
['Green', 'White', 'White', 'Red']

To fix your original code, do

current.append(random.choice(colours))

instead of

current = random.choice(colours)

You should also make current a local variable and return it rather than a global variable. In the same light, you should pass the array of choices as a parameter rather than working on a global variable directory. Both of these changes will give your function greater flexibility.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM