TypeError while operating on list indices in Python

huangapple go评论91阅读模式
英文:

TypeError while operating on list indices in Python

问题

我有以下代码:

(len(parameters) / 2

上述代码返回错误:

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

为什么会出现这种情况 - 特别是我提供的向量的长度是一个可被2整除的整数(实际上,我已经检查了这一点)?

我认为整数在Python中具有精确的表示,所以len(a)/2应该始终返回一个整数。

对此问题的任何帮助都受欢迎。

英文:

I have the following code:

(len(parameters) / 2

The code above returned the error:

TypeError: slice indices must be integers or None or have an __index__ method

Why is this the case - especially the length of the vector I gave is an int which is divisible by 2 (in fact, I check for this)?

I would think integers have exact representations in python, so len(a)/2 should always return an int.

Any help is this matter is welcome.

答案1

得分: 1

即使parameters能够被2整除,len(parameters)/2将返回一个float。请使用len(parameters)//2将其转换为int

有关更多信息,请参阅Numeric Types

英文:

Even if the parameters is divisible by 2 without a remainder, the len(parameters)/2 will return a float. Use len(parameters)//2 to cast it into an int.

For more information; Numeric Types.

答案2

得分: 1

len(a)/2 是地板除法。

它总是返回一个浮点数。

你应该使用 整数除法 //

parameters[: (len(parameters) // 2)] 

示例

4/2

2.0

4//2

2
英文:

len(a)/2 is floor division.

It always returns a float.

You should do integer division //

parameters[: (len(parameters) // 2)] 

Example

4/2

2.0

4//2

2

huangapple
  • 本文由 发表于 2023年8月5日 16:43:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76840819.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定