Python 切片索引必须是整数或 None 或具有 __index__ 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20733156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:06:36  来源:igfitidea点击:

Slice indices must be integers or None or have __index__ method

pythonslice

提问by DescampsAu

I'm trying something with Python. I want to slice a list (plateau) in several list (L[i]) but I have the following error message:

我正在用 Python 尝试一些东西。我想在多个列表 (L[i]) 中切片一个列表(高原),但出现以下错误消息:

  File "C:\Users\adescamp\Skycraper\skycraper.py", line 20, in <module>
    item = plateau[debut:fin]
TypeError: slice indices must be integers or None or have an __index__ method

The concerned line is the one with item = plateau[debut:fin]

相关线路是 item = plateau[debut:fin]

from math import sqrt

plateau = [2, 3, 1, 4, 1, 4, 2, 3, 4, 1, 3, 2, 3, 2, 4, 1]

taille = sqrt(len(plateau))

# Division en lignes
L = []
i = 1
while i < taille:
    fin = i * taille
    debut = fin - taille
    item = plateau[debut:fin]
    L.append(item)
    i += 1

采纳答案by Martijn Pieters

Your debutand finvalues are floating point values, not integers, because tailleis a float.

您的debutfin值是浮点值,而不是整数,因为taille是浮点数。

Make those values integers instead:

将这些值改为整数:

item = plateau[int(debut):int(fin)]

Alternatively, make taillean integer:

或者,创建taille一个整数:

taille = int(sqrt(len(plateau)))