简体   繁体   English

在random.choices()中使用索引[0]

[英]Use of index [0] in random.choices()

What is the purpose of using [0] in random.choices() ? random.choices()中使用[0]的目的是什么? Does [0] refer to index of Lists or of its sub-lists in the example code below? 在下面的示例代码中, [0]是否引用Lists或其子列表的索引? If I use [0] , I get the single random word from the lists, which is the desired result, but if I omit [0] , it gives the random sub-list with all of its elements. 如果使用[0] ,则从列表中获得单个随机词,这是期望的结果,但是如果省略[0] ,它将给出具有其所有元素的随机子列表。

Why it is giving the different result for the two cases? 为什么在两种情况下给出不同的结果?

If I try [1] instead of [0] , The code gives 如果我尝试用[1]而不是[0] ,代码将给出

index error: index out of range 索引错误:索引超出范围

But if I use [0] or [-1] , code gives the desired result. 但是,如果我使用[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)

You're using random.choices instead of random.choice , which returns a list with a single element instead of the element itself. 您使用的是random.choices而不是random.choice ,它返回一个列表,其中包含单个元素而不是元素本身。 See here: 看这里:

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

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

Calling [0] on it returns the element, while [1] is out of range because there's only one element. 调用[0]会返回该元素,而[1]超出范围是因为只有一个元素。 You probably wanted to use random.choice (without the s), right? 您可能想使用random.choice (不带s),对吗?

BTW, random.choices is Python 3.6+. 顺便说一句, random.choices是Python 3.6+。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM