简体   繁体   中英

How to create a small random list from a larger list with Python

I want to create a list containing three items randomly chosen from a list of many items. This is how I have done it, but I feel like there is probably a more efficient (zen) way to do it with python.

import random

words = ['bacon', 'gorilla', 'phone', 'hamburger', 'mother']

small_list = []

while len(small_list) < 4:
    word = random.choice(words)
    if word not in small_list:
        small_list.append(word)

Expected output would be something like:

small_list = ['phone', 'bacon', 'mother']

Use random.sample :

Return ak length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.

import random

words = ['bacon', 'gorilla', 'phone', 'hamburger', 'mother']
small_list = random.sample(words, k=3)

print(small_list)
# ['mother', 'bacon', 'phone']

From this answer , you can use random.sample() to pick a set amount of data.

small_list = random.sample(words, 4)

Demo

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