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”。
添加回答
舉報