另一种选择,不使用索引累加器,但仍要求索引按升序排列。
newObjects = ["a", "b", "c"]
newObjectIndices = [0, 2, 4]
existingList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for index, obj in zip(reversed(newObjectIndices), reversed(newObjects)):
existingList.insert(index, obj)
print(existingList) # ['a', 0, 1, 'b', 2, 3, 'c', 4, 5, 6, 7, 8, 9]
如果不能保证升序,那么排序是一种可能的解决方案。
newObjects = ["b", "a", "c"]
newObjectIndices = [2, 0, 4]
existingList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for index, obj in reversed(sorted( zip(newObjectIndices, newObjects), key=lambda tup: tup[0])):
existingList.insert(index, obj)
print(existingList) # ['a', 0, 1, 'b', 2, 3, 'c', 4, 5, 6, 7, 8, 9]