[英]Use of index [0] in random.choices()
在random.choices()
中使用[0]
的目的是什么? 在下面的示例代码中, [0]
是否引用Lists
或其子列表的索引? 如果使用[0]
,则从列表中获得单个随机词,这是期望的结果,但是如果省略[0]
,它将给出具有其所有元素的随机子列表。
为什么在两种情况下给出不同的结果?
如果我尝试用[1]
而不是[0]
,代码将给出
索引错误:索引超出范围
但是,如果我使用[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
,它返回一个列表,其中包含单个元素而不是元素本身。 看这里:
In [3]: random.choices("abc")
Out[3]: ['a']
In [4]: random.choice("abc")
Out[4]: 'b'
调用[0]
会返回该元素,而[1]
超出范围是因为只有一个元素。 您可能想使用random.choice
(不带s),对吗?
顺便说一句, random.choices
是Python 3.6+。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.