简体   繁体   English

带有字符串作为数据类型的python array.array

[英]python array.array with strings as data type

Is there an object that acts like array.array, yet can handle strings (or character arrays) as its data type? 是否有一个对象类似于array.array,但可以将字符串(或字符数组)作为其数据类型来处理?

It should be able to convert the string array to binary and back again, preferably with null terminated strings, however fixed length strings would be acceptable. 它应该能够将字符串数组转换为二进制并再次返回,最好是使用空终止的字符串,但是固定长度的字符串是可以接受的。

>>> my_array = stringarray(['foo', 'bar'])
>>> my_array.tostring()
'foo\0bar\0'
>>> re_read = stringarray('foo\0bar\0')
>>> re_read[:]
['foo', 'bar']

I will be using it with arrays that contain a couple million strings. 我将其与包含数百万个字符串的数组一起使用。

Simply use a standard Python list: 只需使用标准的Python列表:

def list_to_string(lst):
    return "\0".join(l) + "\0"

def string_to_list(s):
    return s.split("\0")[:-1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM