2 回答

TA贡献1804条经验 获得超2个赞
这里使用一个字典,类型的字典提供O(1)查询相比,list.index这是一个O(N)操作。
这也适用于字符串。
>>> lis = (2,6,4,8,7,9,14,3)
>>> dic = dict(zip(lis, lis[1:]))
>>> dic[4]
8
>>> dic[7]
9
>>> dic.get(100, 'not found') #dict.get can handle key errors
'not found'
创建上述命令的内存有效版本:
>>> from itertools import izip
>>> lis = (2,6,4,8,7,9,14,3)
>>> it1 = iter(lis)
>>> it2 = iter(lis)
>>> next(it2)
2
>>> dict(izip(it1,it2))
{2: 6, 4: 8, 6: 4, 7: 9, 8: 7, 9: 14, 14: 3}

TA贡献1810条经验 获得超4个赞
您可能希望使用字典来建立索引:
# The list
>>> lis = (2,6,4,8,7,9,14,3)
# build the index
>>> index = dict(zip(lis, range(len(lis))))
>>> index
{2: 0, 3: 7, 4: 2, 6: 1, 7: 4, 8: 3, 9: 5, 14: 6}
# Retrieve position by using the index
>>> index[6]
1
>>> lis[index[6]+1]
4
如果列表随时间变化,则必须重建索引。对于更有效的内存解决方案,您可能更喜欢使用izip其他答案中建议的而不是“ zip”。
添加回答
举报