You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python嵌套列表分组报错求助:实现连续同符号元素分组时出现索引越界问题

Fixing the IndexError in Your Python Grouping Function

Hey there! Let's break down why you're hitting that IndexError: list index out of range and fix your code to get the expected output.

The Root Cause of the Error

In your else block, when you do j = j + 1, you're incrementing the index but not adding a new sublist to my_lst first. At that point, my_lst still only has the number of sublists it had before—so my_lst[j] refers to an index that doesn't exist yet. On top of that, my_lst[j].append([lst[i]]) is the wrong approach: you don't want to append a list to a non-existent sublist, you want to add a brand new sublist to my_lst.

Corrected Code

Here's the fixed version of your function, with explanations of the changes:

def num_8(lst):
    # Handle empty input list to avoid errors
    if not lst:
        return []
    
    my_lst = [[lst[0]]]
    j = 0
    
    for i in range(1, len(lst)):
        current_num = lst[i]
        prev_num = lst[i-1]
        
        # Check if current and previous numbers have the same sign
        if (current_num > 0 and prev_num > 0) or (current_num < 0 and prev_num < 0):
            my_lst[j].append(current_num)
        else:
            j += 1
            # Add a new sublist containing the current number to my_lst
            my_lst.append([current_num])
    
    return my_lst

# Test the function with your example input
print(num_8([2,5,-3,-1,-1,3,-2,-2]))

Key Fixes & Improvements

  • Fixed the else block: Instead of trying to access a non-existent index, we use my_lst.append([current_num]) to add a new sublist directly to the main list.
  • Added empty list handling: Prevents a crash if someone passes an empty list as input.
  • Improved readability: Assigned lst[i] and lst[i-1] to descriptive variables so the condition is easier to parse.
  • Removed debug print: Took out the print(my_lst) inside the loop to clean up output (you can add it back for debugging if needed).

A More Streamlined Alternative

If you want to avoid tracking the index j entirely, you can work with a "current group" variable instead. This approach is often easier to follow:

def num_8(lst):
    if not lst:
        return []
    
    result = []
    current_group = [lst[0]]
    
    for num in lst[1:]:
        # Compare current number's sign with the first element of the current group
        if (num > 0 and current_group[0] > 0) or (num < 0 and current_group[0] < 0):
            current_group.append(num)
        else:
            result.append(current_group)
            current_group = [num]
    
    # Don't forget to add the last group to the result
    result.append(current_group)
    return result

Both versions will output your expected result: [[2,5],[-3,-1,-1],[3],[-2,-2]]

内容的提问来源于stack exchange,提问作者Eliza R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 06:53:11