2

我使用索引实例(例如,音乐曲目)进行操作,并且必须通过其索引(int->string)查找对象的名称。字典太慢了(我有大约 10M 个对象)。内存不是问题,因此最方便的解决方案是从带有名称的 csv 文件创建一个随机访问的字符串数组。

但是,我在 python 中没有做到这一点——我收到一个错误,即 0-dim 数组(字符串)无法被索引。为字符串创建随机访问容器的本机 python 方法是什么?

4

1 回答 1

2

据我所知,Python 中的字典的平均访问时间为 O(1),但列表肯定会更快。如果你的索引不是很稀疏,你可以尝试这样的事情:

reader = [(1, 'a'), (2, 'b')] # Replace it with your CSV reader.

# First, fill a dictionary:
text_dict = {}
for index, text in reader:
    text_dict[index] = text

# Then create a sufficiently large list:
max_index = max(text_dict.iterkeys())
texts = [None] * (max_index + 1)

# And fill it:
for index, text in text_dict.iteritems():
    texts[index] = text

print texts
# prints: [None, 'a', 'b']
print texts[1]
# prints: a
于 2011-02-09T14:43:50.467 回答