[英]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.