在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)
您使用的是
random.choices
而不是random.choice
,后者返回一个包含单个元素而不是元素本身的列表。请看这里:调用
[0]
返回元素,而[1]
超出范围,因为只有一个元素。您可能想使用random.choice
(不带s),对吗?你知道吗顺便说一句,^{} 是python3.6+。你知道吗
相关问题 更多 >
编程相关推荐