简体   繁体   English

我正在尝试使用 random.randint 打印列表的随机索引,但我让列表索引超出范围

[英]I am trying to print a random index of the list using random.randint, but Im getting list index out of range

I'm newbie in programming learning Python.我是编程学习Python的新手。 I'm getting started with list.我开始使用列表。 In the following program I am trying to print a random index of the list using random.randint, but Im getting list index out of range.在下面的程序中,我尝试使用 random.randint 打印列表的随机索引,但我让列表索引超出范围。 The random number is given a range which is within the length of the List.随机数的范围在列表的长度内。

import random

members = ["Al, Am, Da, Ma, Sa, Za"]
print("The winner is: " + members[random.randint(0,5)])

Your entire list is just one string.您的整个列表只是一个字符串。 You need to have each element separated by commas to indicate that they're each their own elements.您需要将每个元素用逗号分隔,以表明它们都是自己的元素。

members = ["Al", "Am", "Da", "Ma", "Sa", "Za"]

Welcome to Stackoverflow.欢迎来到 Stackoverflow。 First of all, your list is one string, and you need to separate each string with commas.首先,您的列表是一个字符串,您需要用逗号分隔每个字符串。 After you've done that, your code will work fine.完成此操作后,您的代码将正常工作。 An easier way of choosing a random item in the list is with random.choice(method) which chooses a random element in the data structure you provide.在列表中选择随机项目的一种更简单的方法是使用 random.choice(method) 在您提供的数据结构中选择一个随机元素。 Your finalized code looks like this:您的最终代码如下所示:

 import random members = ["Al", "Am", "Da", "Ma", "Sa", "Za"] print("The winner is: " + random.choice(members))

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

相关问题 除了在索引中使用random.randint()之外,如何从python列表中选择随机字符串? - How do i choose random string from python list other than using random.randint() in index? 使用random.randint()从列表中按索引绘制元素时出现索引错误 - Index error when drawing elements by index from list using random.randint()'s 如何使用 random.randint for 循环创建随机数字列表? - How to create a random list of numbers using a random.randint for loop? 使用randint列出索引超出范围 - List index out of range using randint 为什么我使用 random.randint 生成相同的数字? - Why am I generating the same number using random.randint? 在python中使用random.randint从列表中随机选择 - randomly choose from list using random.randint in python 如何打印出与Random.Randint()函数相同的返回值 - How to print out the same returned value of a Random.Randint() function 我试图使用递归函数将数学方程式中的方括号减少到一个数字,并且我不断使列表索引超出范围错误 - Im trying to reduce brackets in math equations down to one number using a recursive function and I keep getting a list index out of range error 随机出现“ IndexError:列表索引超出范围” - Random “IndexError: list index out of range ” python 随机索引错误:列表索引超出范围 - python random IndexError: list index out of range
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM