繁体   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