标签: index-error

IndexError:当我尝试使用 auto-py-to-exe 从 python 脚本创建可执行文件时,元组索引超出范围

我一直在尝试一个开源的个人人工智能助理脚本。该脚本工作正常,但我想创建一个可执行文件,以便我可以将该可执行文件赠送给我的一位朋友。但是,当我尝试使用 auto-py-to-exe 创建可执行文件时,出现以下错误:

Running auto-py-to-exe v2.10.1
Building directory: C:\Users\Tarun\AppData\Local\Temp\tmpjaw1ky1x
Provided command: pyinstaller --noconfirm --onedir --console --no-embed-manifest  "C:/Users/Tarun/AppData/Local/Programs/Python/Python310/AI_Ass.py"
Recursion Limit is set to 5000
Executing: pyinstaller --noconfirm --onedir --console --no-embed-manifest C:/Users/Tarun/AppData/Local/Programs/Python/Python310/AI_Ass.py --distpath C:\Users\Tarun\AppData\Local\Temp\tmpjaw1ky1x\application --workpath C:\Users\Tarun\AppData\Local\Temp\tmpjaw1ky1x\build --specpath C:\Users\Tarun\AppData\Local\Temp\tmpjaw1ky1x

42681 INFO: PyInstaller: 4.6
42690 INFO: Python: 3.10.0
42732 INFO: Platform: Windows-10-10.0.19042-SP0
42744 INFO: wrote C:\Users\Tarun\AppData\Local\Temp\tmpjaw1ky1x\AI_Ass.spec
42764 INFO: UPX is not available.
42772 INFO: Extending PYTHONPATH with paths
['C:\\Users\\Tarun\\AppData\\Local\\Programs\\Python\\Python310']
43887 INFO: checking Analysis
43891 INFO: Building Analysis because Analysis-00.toc is non existent
43895 INFO: …
Run Code Online (Sandbox Code Playgroud)

python executable tuples pyinstaller index-error

21
推荐指数
2
解决办法
1万
查看次数

沿着第二轴连接2个1D numpy阵列

执行

import numpy as np
t1 = np.arange(1,10)
t2 = np.arange(11,20)

t3 = np.concatenate((t1,t2),axis=1)
Run Code Online (Sandbox Code Playgroud)

结果是

Traceback (most recent call last):

  File "<ipython-input-264-85078aa26398>", line 1, in <module>
    t3 = np.concatenate((t1,t2),axis=1)

IndexError: axis 1 out of bounds [0, 1)
Run Code Online (Sandbox Code Playgroud)

为什么报告轴1超出范围?

arrays numpy concatenation index-error numpy-ndarray

9
推荐指数
4
解决办法
3万
查看次数

如何找出哪个指数超出范围?

如果出现IndexError,有没有办法判断一行上的哪个对象是"超出范围"?

考虑以下代码:

a = [1,2,3]
b = [1,2,3]

x, y = get_values_from_somewhere()

try:
   a[x] = b[y]
except IndexError as e:
   ....
Run Code Online (Sandbox Code Playgroud)

如果x或者y太大而IndexError被抓住,我想知道哪个a或哪个b超出范围(所以我可以在except块中执行不同的操作).

显然,我可以比较x,并ylen(a)len(b)分别,但我很好奇,如果有使用这样做的另一种方式IndexError.

python exception index-error

8
推荐指数
3
解决办法
570
查看次数

'索引0超出轴0的大小为0'是什么意思?

我是python和numpy的新手.我运行了一个我编写的代码,我收到了这条消息:'索引0超出了0号轴的大小为0'没有上下文,我只是想弄明白这意味着什么..问这个可能很傻但它们的轴0和尺寸0是什么意思?index 0表示数组中的第一个值..但我无法弄清楚0和0的意思.

'data'是一个文本文件,在两列中有许多数字.

x = np.linspace(1735.0,1775.0,100)
column1 = (data[0,0:-1]+data[0,1:])/2.0
column2 = data[1,1:]
x_column1 = np.zeros(x.size+2)
x_column1[1:-1] = x
x_column1[0] = x[0]+x[0]-x[1]
x_column1[-1] = x[-1]+x[-1]-x[-2]
experiment = np.zeros_like(x)
for i in range(np.size(x_edges)-2):
    indexes = np.flatnonzero(np.logical_and((column1>=x_column1[i]),(column1<x_column1[i+1])))
    temp_column2 = column2[indexes]
    temp_column2[0] -= column2[indexes[0]]*(x_column1[i]-column1[indexes[0]-1])/(column1[indexes[0]]-column1[indexes[0]-1])
    temp_column2[-1] -= column2[indexes[-1]]*(column1[indexes[-1]+1]-x_column1[i+1])/(column1[indexes[-1]+1]-column1[indexes[-1]])
    experiment[i] = np.sum(temp_column2)   
return experiment
Run Code Online (Sandbox Code Playgroud)

python indexing error-handling numpy index-error

7
推荐指数
3
解决办法
4万
查看次数

IndexError:列表分配索引超出范围 Python 3

有人知道为什么我在这段代码中得到一个 IndexError 吗?

            global gegner
            global gegnerhp
            gegner = []
            gegberhp = []



            for i in range(1,anzahlgegner):
                random = randint(1,5)
                if random == 1:
                    gegner[i] = "goblin"
                    gegnerhp[i] = randint(10,50)
                elif random == 2:
                    gegner[i] = "ghost"
                    gegnerhp[i] = randint(10,50)
                elif random == 3:
                    gegner[i] = "hound"
                    gegnerhp[i] = randint(10,50)
                elif random == 4:
                    gegner[i] = "wolf"                        #LINE 147
                    gegnerhp[i] = randint(10,50)
                elif random == 5:
                    gegner[i] = "goblin"
                    gegnerhp[i] = randint(10, 50)
                print("* {0} with {1} HP".format(gegner[i]),gegnerhp[i])
Run Code Online (Sandbox Code Playgroud)

例如,当随机数为 4 …

python arrays pycharm python-3.x index-error

5
推荐指数
1
解决办法
2万
查看次数

IndexError:位置参数元组的替换索引 1 超出范围

我正在学习教程,但不知道为什么会出现此错误:

    <ipython-input-61-d59f7a5a07ab> in extract_featuresets(ticker)
      2     tickers, df = process_data_for_labels(ticker)
      3     df['{}_target'.format(ticker)] = list(map(buy_sell_hold,
----> 4                                              df['{}_{}1d'.format(ticker)],
      5                                              df['{}_{}2d'.format(ticker)],
      6                                              df['{}_{}3d'.format(ticker)],

IndexError: Replacement index 1 out of range for positional args tuple
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

tickers, df = process_data_for_labels(ticker)
df['{}_target'.format(ticker)] = list(map(buy_sell_hold,
                                         df['{}_{}1d'.format(ticker)],
                                         df['{}_{}2d'.format(ticker)],
                                         df['{}_{}3d'.format(ticker)],
                                         df['{}_{}4d'.format(ticker)],
                                         df['{}_{}5d'.format(ticker)],
                                         df['{}_{}6d'.format(ticker)],
                                         df['{}_{}7d'.format(ticker)],))
Run Code Online (Sandbox Code Playgroud)

这是教程的链接:https : //www.youtube.com/watch?v=zPp80YM2v7k

python index-error

4
推荐指数
2
解决办法
2万
查看次数

Pathlib 使用 Path.parents 访问 Path 时出错

为什么当我在 Python IDE (PyCharm) 中运行以下代码片段时:

import os
from pathlib import Path

if os.path.isfile('shouldfail.txt'):
    p = Path(__file__).parents[0]
    p2 = Path(__file__).parents[2]
    path_1 = str(p)
    path_2 = str(p2)

    List = open(path_1 + r"/shouldfail.txt").readlines()
    List2 = open(path_2 + r"/postassembly/target/generatedShouldfail.txt").readlines()
Run Code Online (Sandbox Code Playgroud)

它工作正常并返回所需的结果,但是当我通过命令行运行脚本时,出现错误:

File "Script.py", line 6, in <module>
    p2 = Path(__file__).parents[2]
  File "C:\Users\Bob\AppData\Local\Programs\Python\Python36\lib\pathlib.py", line 594, in __getitem__
    raise IndexError(idx)
IndexError: 2
Run Code Online (Sandbox Code Playgroud)

我在这里缺少什么?还有一种更好/更简单的方法可以从我运行脚本的当前路径向上移动两个文件夹(在脚本内)?

python pycharm python-3.x pathlib index-error

2
推荐指数
1
解决办法
2178
查看次数

尝试访问最后一个索引时出现索引超出范围错误

我正在执行leetcode,我的代码给了我我无法理解的错误。我被要求反转整数,这很容易做到。这些是测试用例:

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21
Run Code Online (Sandbox Code Playgroud)

我发现我所需要的只是if语句来检查输入的条件,所以这就是我所做的:

class Solution:
    def reverse(self, x: int) -> int:
        string = str(x)
        lst = list(string)

        lst.reverse()

        if((lst[0]) == '0'):
            lst.pop(0)

        if((lst[-1] == '-')):
            lst.pop(-1)
            lst.insert(0, '-')

        output = ''.join(lst)

        return output
Run Code Online (Sandbox Code Playgroud)

但是这一行if((lst[-1] == '-')):抛出一个IndexError: list index out of range错误。我正在做的是访问列表的最后一个元素。我不尝试访问不存在的索引。

我唯一需要知道的是为什么会发生此错误。因为这是leetcode,所以我想自己修复该代码。

最终密码

class Solution:
    def reverse(self, x: int) -> int:
        lst = list(str(x))

        lst.reverse()

        if(x < 0):
            lst.pop(-1) …
Run Code Online (Sandbox Code Playgroud)

python index-error

1
推荐指数
1
解决办法
46
查看次数

Python捕获异常但打印它们

我已经建立了一个最大堆,并尝试提取max,只要有元素.如果没有我正在返回IndexError.这是我正在尝试执行的代码:

while True:
    try:
        print hp.extract_max()
    except:
        break
Run Code Online (Sandbox Code Playgroud)

并在extract_max()方法中:

def extract_max(self):
    if self.size == 0:
        return IndexError
    item = self.items[0]
    self.items[0] = self.items[self.size - 1]
    self.heapify_down()
    del self.items[len(self.items) - 1]
    return item
Run Code Online (Sandbox Code Playgroud)

但是,代码在遇到IndexError时没有破坏,而是打印它.在同时循环不打破.

<type 'exceptions.IndexError'>
<type 'exceptions.IndexError'>
....
Run Code Online (Sandbox Code Playgroud)

它不断打印异常,而不会打破循环.

有什么问题?

python heap loops exception index-error

0
推荐指数
1
解决办法
50
查看次数

我不知道为什么会出现此错误或索引超出范围。我在 jupyter 笔记本中使用 Python 3.0

import random
from IPython.display import clear_output

dictionary = open("words_50000.txt","r")
dict_5000 = dictionary.readlines()
guess = random.choice(dict_5000).lower().strip('\n')
no_of_letters = len(guess)
game_str = ['-']*no_of_letters
only_length=[]

def word_guesser():
    only_length_words()
    print(dict_5000)


def only_length_words():
    for i in range(len(dict_5000)):
        if len(dict_5000[i].strip('\n'))!=no_of_letters:
            dict_5000.pop(i)    

word_guesser()
Run Code Online (Sandbox Code Playgroud)

-------------------------------------------------- ------------------------- IndexError Traceback (最近一次调用) in () 20 dict_5000.pop(i) 21 ---> 22 word_guesser ()

在 word_guesser() 11 12 def word_guesser(): ---> 13 only_length_words() 14 print(dict_5000) 15

在 only_length_words() 17 def only_length_words(): 18 for i in range(len(dict_5000)): ---> 19 if len(dict_5000[i].strip('\n'))!=no_of_letters: 20 dict_5000。流行音乐(一) 21

IndexError:列表索引超出范围

python jupyter-notebook index-error

0
推荐指数
1
解决办法
139
查看次数

从 1 而不是 0 开始索引

我无法以起始索引 1 初始化数组。我使用了插入附加,并且我希望索引以 1 而不是 0 开头:

n=int(input('enter '))
array=[]
for i in range(1,n+1):
    print(i)
    element=int(input('element '))
    array.insert(i,element)
    #array.append(element)
    print(i,array[i])
Run Code Online (Sandbox Code Playgroud)

这给出了一个IndexError例外print(i,array[i])list index out of range.

python index-error

-1
推荐指数
1
解决办法
1万
查看次数