在中使用索引[0]随机选择()

2024-04-23 11:30:11 发布

您现在位置:Python中文网/ 问答频道 /正文

random.choices()中使用[0]的目的是什么?在下面的示例代码中,[0]是指Lists的索引还是其子列表的索引?如果我使用[0],我会从列表中得到一个随机词,这是期望的结果,但是如果我省略[0],它会给出随机子列表及其所有元素。你知道吗

为什么对这两种情况给出不同的结果?你知道吗

如果我尝试[1]而不是[0],代码会给出

index error: index out of range

但是如果我使用[0][-1],代码会给出所需的结果。你知道吗

import random

Animals = ["Cat", "Dog", "Lion", "Tiger", "Elephant"]
Fruits = ["Apple", "Orange", "Banana", "Mango", "Pineapple"]
Vegetables = ["Tomato", "Potato", "Onion", "Brinjal", "Peas"]

Lists = [Animals, Fruits, Vegetables]

word = random.choice(random.choices(Lists)[0])

print(word)

Tags: 代码目的元素示例列表indexrandomlists
1条回答
网友
1楼 · 发布于 2024-04-23 11:30:11

您使用的是random.choices而不是random.choice,后者返回一个包含单个元素而不是元素本身的列表。请看这里:

In [3]: random.choices("abc")
Out[3]: ['a']

In [4]: random.choice("abc")
Out[4]: 'b'

调用[0]返回元素,而[1]超出范围,因为只有一个元素。您可能想使用random.choice(不带s),对吗?你知道吗

顺便说一句,^{}是python3.6+。你知道吗

相关问题 更多 >