原文链接:http://www.juzicode.com/python-error-slice-indices-must-be-integers-none-index-method
错误提示:
列表切片索引时提示:TypeError: slice indices must be integers or None or have an __index__ method
#juzicode.com/vx:桔子code
lst = [0,1,2,3,4,5,6,7,8,9]
half = len(lst)/2
print('lst:',lst)
print('lst[:half]:',lst[:half])
==========运行结果:
lst: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-37-9781b7347c18> in <module>
3 half = len(lst)/2
4 print('lst:',lst)
----> 5 print('lst[:half]:',lst[:half])
TypeError: slice indices must be integers or None or have an __index__ method
错误原因:
1、half = len(lst)/2 得到的数值为float类型,不能作为列表索引的下标,需要先转换为整数类型
解决方法:
1、half = len(lst)/2 改为 half = int(len(lst)/2)
#juzicode.com/vx:桔子code
lst = [0,1,2,3,4,5,6,7,8,9]
half = int(len(lst)/2)
print('lst:',lst)
print('lst[:half]:',lst[:half])
==========运行结果:
lst: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
lst[:half]: [0, 1, 2, 3, 4]
扩展内容:
如果本文还没有完全解决你的疑惑,你也可以在微信公众号“桔子code”后台给我留言,欢迎一起探讨交流。