1
1

More than 3 years have passed since last update.

Python スライス指定で変数を使う際の注意点

Last updated at Posted at 2020-12-02

python: エラー 「slice indices must be integers or None or have an __index__ method」が出た時の解決法

pythonにて以下のエラーが出たので、その際の対応記録です。

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

エラーコード

観測データの解析でfftを使うときに以下のようなコードでエラーが出ました。

fft.py
freq = [0,1,2,3,4,5,6]    #リスト
fft_sampling = 7
a = fft_sampling/2    #スライス用
out = freq[1:a]

リストをスライスする際は整数か__index__ methodで指定をしないとだめらしい。

解決策

思いついたところでは以下の3種類です。

  • fft_sampling/2fft_sampling//2と指定することで、fft_samplingがいくつでもスライスを整数で指定ができる。:「//」⇒余りを切り捨て、商のみ
fft.py
freq = [0,1,2,3,4,5,6]    #リスト
fft_sampling = 7   
a = fft_sampling//2    #スライス用
out = freq[1:a]
#out = [1,2]
print(a)
#3
  • mathモジュールのfloor()関数かceil()関数を使う。:floor()⇒小数点切り下げ, ceil()⇒小数点切り上げ
fft.py
import math

freq = [0,1,2,3,4,5,6]    #リスト
fft_sampling = 7
a = math.floor(fft_sampling/2)    #切り捨て
b = math.ceil(fft_sampling/2)    #切り上げ
out = freq[1:a]
#out = [1,2]
out = freq[1:b]
#out = [1,2,3]
print(a)
#3
print(b)
#4
  • int()で小数点以下を切り捨てる。
fft.py
freq = [0,1,2,3,4,5,6]    #リスト
fft_sampling = 7   
a = int(fft_sampling/2)    #スライス用
out = freq[1:a]
#out = [1,2]
print(a)
#3

round()関数では丸め方が少し面倒になるので使わないほうがわかりやすそうです。

注釈 浮動小数点数に対する round() の振る舞いは意外なものかもしれません: 例えば、 round(2.675, 2) は予想通りの 2.68 ではなく 2.67 を与えます。これはバグではありません: これはほとんどの小数が浮動小数点数で正確に表せないことの結果です。詳しくは 浮動小数点演算、その問題と制限 を参照してください。
公式ドキュメントから引用

リストの指定の際も同様

単にリストの指定の際にも同様のことが起こるので注意

list.py
list = [0,1,2,3,4,5,6]    #リスト
num = 7   
a = num/2    #スライス用
out = freq[a]
#TypeError: slice indices must be integers or None or have an __index__ method
print(a)
#3.5

b = num//2 
out = freq[b]
#out = [1,2]
print(b)
#3

参考にさせていただいた記事

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1