簡體   English   中英

在 python 列表中選擇多個元素

[英]choosing multiple element in python list

如何從列表中選擇隨機多個元素? 我從互聯網上查看但找不到任何東西。

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

您可以使用random.sample()來實現:

from random import sample

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

這將從單詞列表中隨機 select 2 個單詞。 您可以查看 Python文檔了解更多詳細信息。

我想:

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

您可以將 1/2 調整為 0 到 1 之間的任何值,以近似初始列表中所選單詞的百分比。

使用random

這是示例

  • 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 需要一個額外的參數來傳遞一個返回元素的列表
>>> 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']

您可以使用random

方法 1 - random.choice()

from random import choice

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

方法 2 - 生成隨機索引

from random import randint

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

方法 3 - Select 多個項目

from random import choices

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM