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

XML特征提取时列表切片求和出现slice indices错误的原因及解决方法

解决Python中TypeError: slice indices must be integers的问题

Hey there, let's break down this error and fix it step by step.

错误原因分析

The error TypeError: slice indices must be integers or None or have an __index__ method pops up because you're using a float value (Number_MBLK_per_frame) to calculate slice positions for the QPY_float list.

Python requires integer indices for list slices—you can't use decimal numbers to point to positions in a list. Even though you explicitly converted Number_MBLK_per_frame to float, that's exactly what's causing the crash here.

Plus, think about what this variable represents: the number of macroblocks per frame. That should always be a whole number (you can't have a fraction of a macroblock), so converting it to float doesn't make logical sense either.

解决方法

Here are two key fixes you need to apply:

  • Convert Number_MBLK_per_frame to an integer: Since macroblock counts are whole numbers, use integer division or explicitly cast the result to an int instead of float.
  • Fix the slice range logic: Your current slice excludes the last macroblock of each frame. Adjust the range to capture all macroblocks in the target frame.

修改后的代码片段

Here's how to update the relevant parts of your code:

# Replace the float conversion line with integer division
Number_MBLK_per_frame = len(QPY) // len(frame_Num)
# Alternatively, you can use explicit int casting:
# Number_MBLK_per_frame = int(len(QPY) / len(frame_Num))

# Then correct the slice in each if block (example shown for I frames, repeat for P/B):
if PBI[j] == "2":  # I_frame
    # Fixed slice range to include all macroblocks in the frame
    QPY_framesum[2] += sum(QPY_float[j*Number_MBLK_per_frame : (j+1)*Number_MBLK_per_frame])
    QPY_framenum[2] += 1

额外建议

To avoid edge cases where the total macroblock count isn't evenly divisible by the number of frames, add a quick check:

if len(QPY) % len(frame_Num) != 0:
    print(f"Warning: Uneven macroblock count detected in file {pname}")

This will alert you to cases where your assumption of equal macroblocks per frame doesn't hold, preventing unexpected errors down the line.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 13:02:32