itertools无法将numpy ints识别为Python 3.6上的有效输入 [英] itertools does not recognize numpy ints as valid inputs on Python 3.6

查看:313
本文介绍了itertools无法将numpy ints识别为Python 3.6上的有效输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此代码:

import itertools as it
import numpy as np
data = ['a','b','c','d']
dw = np.array([1, 3], dtype=np.int64)
print(list(it.islice(data,dw[0],dw[1],1)))

在Python 2.7上,它按预期打印['b', 'c',].

On Python 2.7 it prints ['b', 'c',] as expected.

在Python 3.6上,它将引发异常:

On Python 3.6 it throws an exception:

ValueError: Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize.

np.int32也是一样,itertools包的其他方法也会引发类似的错误,例如当您使用permutations时,您会得到TypeError: Expected int as r.

The same goes for np.int32, and other methods of the itertools package throw similar errors, e.g. when you use permutations you get TypeError: Expected int as r.

除了此numpy问题和相关的问题之外,我在此方面找不到更多的东西,但那是3年前被关闭的,这意味着它已经解决了.

I couldn't find much on this apart from this numpy issue and related ones, but that one was closed 3 years ago implying it was solved.

使用numpy int data[dw[0]]进行索引或使用dw[0] == 1这样的布尔比较等基本功能都可以正常工作.

And basic things like indexing with numpy ints data[dw[0]] or boolean comparisons like dw[0] == 1 work just fine.

我错过了什么吗?这可能是Python 3错误吗?

Am I missing something? Could this be a Python 3 bug?

推荐答案

一个numpy.int64显然不是int

a, b = dw[0], dw[1]

type(a)

numpy.int64

isinstance(a, int)

False

Numpy文档

文档明确提到了这一点

Numpy documentation

The documentation mentions this explicitly

警告

int_类型不会从Python 3内置的int继承, 因为int类型不再是固定宽度的整数类型.

The int_ type does not inherit from the int built-in under Python 3, because type int is no longer a fixed-width integer type.

解决方案

print(list(it.islice(data, int(dw[0]) , int(dw[1]), 1)))

或numpy切片

data[dw[0]:dw[1]:1]

这篇关于itertools无法将numpy ints识别为Python 3.6上的有效输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆