简体   繁体   English

得到“ IndexError:列表索引超出范围”

[英]Getting “IndexError: list index out of range”

I'm wondering why this error comes up, IndexError: list index out of range. 我想知道为什么会出现此错误,IndexError:列表索引超出范围。 If the full program is required then I will upload, but the error is in this part of the code. 如果需要完整的程序,那么我将上载,但是错误在代码的这一部分。

import random
Sign = ["+-*"]
num = int(random.random()*2)
operator = (Sign[num])
digit = int(random*10)

This is meant to output a random sign of the array. 这意味着输出数组的随机符号。

random.random() returns a floating point number which is greater than 0 and less than 1, so int(random.random()*2) will only ever result in 0 or 1. The random module has a specific function to return random integers in a specified range, which is simpler to use than "rolling your own" random integer algorithm (and with results that are generally more uniform). random.random()返回一个大于0且小于1的浮点数,因此int(random.random()*2)只会返回0或random模块具有一个特定的函数来返回random指定范围内的整数,比使用“滚动自己的”随机整数算法(结果通常更统一)更容易使用。

But random also has a function to return a random member of a sequence (eg a str, tuple or list), so it's appropriate to use that to select your random operator. 但是random还具有返回序列的随机成员(例如,str,tuple或list)的功能,因此使用它来选择您的随机运算符是适当的。 Eg, 例如,

#! /usr/bin/env python

import random

sign = "+-*"

for i in range(10):
    op = random.choice(sign)
    digit = random.randint(0, 9)
    print op, digit

typical output 典型输出

+ 7
* 9
+ 0
* 6
* 8
* 5
+ 0
- 1
- 6
- 3

I changed the variable name to op in that code because operator is the name of a standard module. 我在该代码中将变量名称更改为op ,因为operator是标准模块的名称。 It's not an error to use that name for your own variables, but it will definitely cause problems if you did want to import that module. 为您自己的变量使用该名称不是一个错误,但是如果您确实要导入该模块,则肯定会导致问题。 And it's also confusing to people reading your code. 这也使人们在阅读您的代码时感到困惑。

Your list only contains one element. 您的列表仅包含一个元素。 Try this: 尝试这个:

Sign = ["+", "-", "*"]

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

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