简体   繁体   中英

choosing multiple element in python list

How can i choose random multiple elements from list? I looked it from internet but couldn't find anything.

words=["ar","aba","oto","bus"]

You could achieve that with random.sample() :

from random import sample

words = ["ar", "aba", "oto", "bus"]
selected = sample(words, 2)

That would select 2 words randomly from the words list. You can check Python docs for more details.

I think about that:

import random as rd
words=["ar","aba","oto","bus"]
random_words = [word for word in words if rd.random()>1/2]

You can adjust 1/2 by any value between 0 and 1 to approximate the percentage of words chosen in the initial list.

Use random

Here is example

  • random.choice
>>> import random
>>> words=["ar","aba","oto","bus"]
>>> print(random.choice(words))
ar
>>> print(random.choice(words))
ar
>>> print(random.choice(words))
oto
>>> print(random.choice(words))
aba
>>> print(random.choice(words))
ar
>>> print(random.choice(words))
bus
  • random.sample # sample takes one extra argument to pass a list with element is returned
>>> print(random.sample(words, 3))
['bus', 'ar', 'oto']
>>> print(random.sample(words, 3))
['ar', 'oto', 'aba']
>>> print(random.sample(words, 2))
['aba', 'bus']
>>> print(random.sample(words, 2))
['ar', 'aba']
>>> print(random.sample(words, 1))
['ar']
>>> print(random.sample(words, 1))
['ar']
>>> print(random.sample(words, 1))
['oto']
>>> print(random.sample(words, 1))
['bus']

You can use random library

Method 1 - random.choice()

from random import choice

words=["ar","aba","oto","bus"]
word = choice(words)
print(word)

Method 2 - Generate Random Index

from random import randint

words=["ar","aba","oto","bus"]
ind = randint(0, len(words)-1)
word = words[ind]
print(word)

Method 3 - Select Multiple Items

from random import choices

words=["ar","aba","oto","bus"]
selected = choices(words, k=2)   # k is the elements count to select
print(selected)

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