简体   繁体   中英

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

What is the purpose of using [0] in random.choices() ? Does [0] refer to index of Lists or of its sub-lists in the example code below? 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.

Why it is giving the different result for the two cases?

If I try [1] instead of [0] , The code gives

index error: index out of range

But if I use [0] or [-1] , code gives the desired result.

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. 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. You probably wanted to use random.choice (without the s), right?

BTW, random.choices is Python 3.6+.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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