Tuple index out of range python что значит
Перейти к содержимому

Tuple index out of range python что значит

  • автор:

Как исправить ошибку «tuple index out of range»?

написал код,который считывает определенные данные с файла и записывает их в excell,но когда я его запускаю,выходит ошибка:
Traceback (most recent call last):
File «C:\Users\Артур\PycharmProjects\pythonProject3\lolik.py», line 10, in
sheet[row][1].value = movie[‘year’]
IndexError: tuple index out of range

Подскажите,как исправить эту ошибку?
код:

1 2 3 4 5 6 7 8 9 10 11 12
import openpyxl import json with open('loxhok.json') as file: data = json.load(file) book=openpyxl.Workbook() sheet = book.active row = 2 for movie in data['movies']: sheet[row][0].value = movie['title'] sheet[row][1].value = movie['year'] book.save("my_book.xlsx") book.close()

Ошибка IndexError: tuple index out of range

Пытался написать магазин для Discord Бота на Python и столкнулся с ошибкой «IndexError: tuple index out of range» В бд уже есть несколько товаров Вот код:

client = commands.Bot( command_prefix = '%') connection = sqlite3.connect('server.db') cursor = connection.cursor() @client.event async def on_ready(): cursor.execute("""CREATE TABLE IF NOT EXISTS shop ( who TEXT, id INT, cost BIGINT ) """) @client.command(aliases = ['shop']) async def __shop(ctx): embed = discord.Embed(title='Shop', colour = discord.Color.green()) embed.set_footer(text = 'Request by <>'.format(ctx.author.name), icon_url = ctx.author.avatar_url) for row in cursor.execute("SELECT id, cost FROM shop"): embed.add_field( name = f'Стоимость ** :dollar:**', value = f'Вы приобретете ', inline = False ) await ctx.send(embed = embed) 

Вот текст ошибки: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: tuple index out of range

Why is this code throwing a ‘tuple index out of range’ error?

I got this error once yesterday but not since I finalized the function. Now I’m making more of the same buttons for similar but different functions, and now the first one is throwing this:

experiment.blend/bake_script", line 71, in execute IndexError: tuple index out of range 

There isn’t any tuple in this code, as far as I can tell.

for mat in obj.data.materials: mat.use_nodes = True #Here it is assumed that the materials have been created with nodes, otherwise it would not be possible to assign a node for the Bake, so this step is a bit useless bake_one.is_active_output = True mat.node_tree.links.new(skin_comp.outputs[0], bake_one.inputs[0]) linkToDelete = baked_BSDF.inputs[0].links[0] mat.node_tree.links.remove(linkToDelete) bump_main.mute = True texture_node = diffuse texture_node.select = True nodes.active = texture_node texture_node.image = imgbake #Assign the image to the node 

enter image description here

The line that’s throwing the error is linkToDelete = baked_BSDF.inputs[0].links[0] There are two mysteries here: 1: Why is it throwing this error today, when it wasn’t yesterday? 2: Why does it think it’s getting a tuple in this? Edit: It’s this connection in particular, but I’m having the same issue with the new button I’m making too. It occurred to me that maybe the nodes are listing connections as tuples, but then 0,0 should be within that list.

MisterLBlends
asked Oct 26, 2022 at 19:05
MisterLBlends MisterLBlends
103 8 8 bronze badges

$\begingroup$ I think both questions are legitimate but neither will help you solve your problem 🙂 Without having access to the file or showing a screenshot of the node editor, it’s only a wild guess, but at first glance I’d say either your baked_BSDF doesn’t have any input which seems unlikely, or its first input isn’t linked to any other node, which is possible. Are you sure you’re in a scenario where this node has a link to another node ? $\endgroup$

Oct 26, 2022 at 19:19
$\begingroup$ I’ve added a screenshot, and some further musings. $\endgroup$
Oct 26, 2022 at 19:27

$\begingroup$ I just tried something that worked, but I don’t know why it worked. I switched from using my defs, to calling the node directly, and it worked. Then I switched back to using the defs, and now it works. Maybe I should call it in the in-module defs instead of in the main script defs? $\endgroup$

Oct 26, 2022 at 19:36

$\begingroup$ It depends on what you mean by «defs» 🙂 but yeah it’s better not to rely too much on variables that are way outside the scope of your functions. Nodes are easily fetched from the node tree by name if need be. $\endgroup$

Oct 26, 2022 at 19:59

$\begingroup$ you can test if a socket is linked to at least one other socket with if node.inputs[0].links: for example. It will evaluate to False if links is empty (ie length 0, no link) $\endgroup$

Oct 26, 2022 at 20:12

1 Answer 1

$\begingroup$

Many thanks to Gorgious for helping me formulate an elegant solution to this problem.

I’m still not entirely sure why the node connections are listed in a way that requires this, but the solution turns out to be fairly simple. Rather than trying to define all possible connections in a block for the entire script to use, you define them ad-hoc for each function.

Also, to avoid the problem of the script failing if the connection happens to not exist, you can use an if statement to either confirm or skip the step.

Here’s the full code of one module:

class WM_OT_Bake_Diffuse(Operator): bl_label = "Bake Diffuse" bl_idname = "wm.bake_diffuse" bl_options = @classmethod def poll(cls, context): return True def execute(self, context): size = bpy.data.scenes["Scene"].bake_tool.bake_int, bpy.data.scenes["Scene"].bake_tool.bake_int obj = bpy.context.active_object diffuse = bpy.data.materials["Skin"].node_tree.nodes["DiffuseBake"] imgbake = bpy.data.images.new("DiffuseBake", width=size[0], height=size[1]) BSDF = bpy.data.materials["Skin"].node_tree.nodes["Baked_BSDF"] # set bake type and parameters for mat in obj.data.materials: mat.use_nodes = True #Here it is assumed that the materials have been created with nodes, otherwise it would not be possible to assign a node for the Bake, so this step is a bit useless bake_one.is_active_output = True mat.node_tree.links.new(skin_comp.outputs[0], bake_one.inputs[0]) if BSDF.inputs[0].links: # Checks if the connection in question exists, skips the step if it doesn't. linkToDelete = BSDF.inputs[0].links[0] mat.node_tree.links.remove(linkToDelete) # the rest of this script sets up the bake, bakes the appropriate image, then reconnects everything. bump_main.mute = True texture_node = diffuse texture_node.select = True nodes.active = texture_node texture_node.image = imgbake #Assign the image to the node bpy.context.view_layer.objects.active = obj bpy.ops.object.bake(type='DIFFUSE', save_mode='EXTERNAL') imgbake.filepath_raw = "//bakes/DiffuseBake.png" imgbake.file_format = 'PNG' imgbake.save() # find node and assign the texture to it img = bpy.data.images.load("//bakes/DiffuseBake.png", check_existing=True) bpy.data.materials["Skin"].node_tree.nodes["DiffuseBake"].image = img bpy.data.images["DiffuseBake"].colorspace_settings.name = 'sRGB' mat.node_tree.links.new(diffuse.outputs[0], baked_BSDF.inputs[0]) bump_main.mute = False return

Что означает ошибка IndexError: list index out of range

Ситуация: у нас есть проект, в котором мы математически моделируем игру в рулетку. Мы хотим обработать отдельно нечётные числа, которые есть на рулетке, — для этого нам нужно выбросить из списка все чётные. Проверка простая: если число делится на 2 без остатка — оно чётное и его можно удалить. Для этого пишем такой код:

# в рулетке — 36 чисел, не считая зеро numbers = [n for n in range(36)] # перебираем все числа по очереди for i in range(len(numbers)): # если текущее число делится на 2 без остатка if numbers[i] % 2 == 0: # то убираем его из списка del numbers[i]

Но при запуске компьютер выдаёт ошибку:

❌ IndexError: list index out of range

Почему так произошло, ведь мы всё сделали правильно?

Что это значит: компьютер на старте цикла получает и запоминает одну длину списка с числами, а во время выполнения эта длина меняется. Компьютер, держа в памяти старую длину, пытается обратиться по номерам к тем элементам, которых уже нет в списке.

Когда встречается: когда программа одновременно использует список как основу для цикла и тут же в цикле добавляет или удаляет элементы списка.

В нашем примере случилось вот что:

  1. Мы объявили список из чисел от 1 до 36.
  2. Организовали цикл, который зависит от длины списка и на первом шаге получает его размер.
  3. Внутри цикла проверяем на чётность, и если чётное — удаляем число из списка.
  4. Фактический размер списка меняется, а цикл держит в голове старый размер, который больше.
  5. Когда мы по старой длине списка обращаемся к очередному элементу, то выясняется, что список закончился и обращаться уже не к чему.
  6. Компьютер останавливается и выводит ошибку.

Что делать с ошибкой IndexError: list index out of range

Основное правило такое: не нужно в цикле изменять элементы списка, если список используется для организации этого же цикла.

Если нужно обработать список, то результаты можно складывать в новую переменную, например так:

# в рулетке — 36 чисел, не считая зеро numbers = [n for n in range(36)] # новый список для нечётных чисел new_numbers = [] # перебираем все числа по очереди for i in range(len(numbers)): # если текущее число не делится на 2 без остатка if numbers[i] % 2 != 0: # то добавляем его в новый список new_numbers.append(numbers[i])

Погружение в аналитику и бигдату: узнайте всё о вашей будущей профессии

Скачайте бесплатный гид журнала «Код», чтобы ответить на все вопросы о старте в направлении «Аналитика и данные»

Погружение в аналитику и бигдату: узнайте всё о вашей будущей профессии

Получите ИТ-профессию

В «Яндекс Практикуме» можно стать разработчиком, тестировщиком, аналитиком и менеджером цифровых продуктов. Первая часть обучения всегда бесплатная, чтобы попробовать и найти то, что вам по душе. Дальше — программы трудоустройства.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *