san*_*san 5 python numpy stringio
这样可以更好地理解事物.这不是我需要解决的实际问题.一个cstringIO
对象应该模拟一个字符串,文件以及一行上的迭代器.它是否也模拟缓冲区?在任何情况下,理想情况下,应该能够构建如下的numpy数组
import numpy as np
import cstringIO
c = cStringIO.StringIO('\x01\x00\x00\x00\x01\x00\x00\x00')
#Trying the iterartor abstraction
b = np.fromiter(c,int)
# The above fails with: ValueError: setting an array element with a sequence.
#Trying the file abstraction
b = np.fromfile(c,int)
# The above fails with: IOError: first argument must be an open file
#Trying the sequence abstraction
b = np.array(c, int)
# The above fails with: TypeError: long() argument must be a string or a number
#Trying the string abstraction
b = np.fromstring(c)
#The above fails with: TypeError: argument 1 must be string or read-only buffer
b = np.fromstring(c.getvalue(), int) # does work
Run Code Online (Sandbox Code Playgroud)
我的问题是它为什么会这样.
这出现的实际问题如下:我有一个产生元组的迭代器.我有兴趣从元组的一个组件制作一个numpy数组,尽可能少复制和复制.我的第一个切入是继续将生成的元组的有趣组件写入StringIO对象,然后将其内存缓冲区用于数组.我当然可以使用,getvalue()
但会创建并返回一份副本.什么是避免额外复制的好方法.
问题似乎是 numpy 不喜欢给出字符而不是数字。请记住,在 Python 中,单个字符和字符串具有相同的类型 \xe2\x80\x94 numpy 必须在幕后进行某种类型检测,并视为'\\x01'
嵌套序列。
另一个问题是 acStringIO
迭代它的行,而不是它的字符。
像下面这样的迭代器应该可以解决这两个问题:
\n\ndef chariter(filelike):\n octet = filelike.read(1)\n while octet:\n yield ord(octet)\n octet = filelike.read(1)\n
Run Code Online (Sandbox Code Playgroud)\n\n像这样使用它(注意搜索!):
\n\nc.seek(0)\nb = np.fromiter(chariter(c), int)\n
Run Code Online (Sandbox Code Playgroud)\n