如何一次性按索引将多个值插入到列表中

11
我想知道是否有一种方法可以使用相同的索引一次将多个变量插入列表中。例如,假设我们有一个列表: [a, b, c][0,1,2,3,4] 而我想要插入第一个列表,使最终结果为: [a, 0, 1, b, 2, 3, c, 4] 但是如果我要使用list.insert(pos, value)逐个进行,使用的位置[0, 2, 4]会变得无效,因为它与旧的5个元素列表相关联,而现在是6个。
有什么建议吗?
4个回答

7

一个简单的选择是从具有最高值的位置开始添加项目,然后继续使用第二高的值等。

这样您可以使用原始方法,而不会出现“旧/新位置”的任何问题。


1
简单易懂,我喜欢它。我本来想创建一个完整的职位索引,但这是迄今为止最好的解决方案。 - SurpriseDog

7
list_a = [0,1,2,3,4]
list_b = ["a", "b", "c"]
pos    = [0, 2, 4]

assert(len(list_b) == len(pos))
acc = 0
for i in range(len(list_b)):
    list_a.insert(pos[i]+acc, list_b[i])
    acc += 1

print(list_a)

['a', 0, 1, 'b', 2, 3, 'c', 4]


这个完美地运作了。只是想提醒其他人,它只有在位置及其相应元素正确排序的情况下才能正常工作,所以如果你有例如[3, 0, 2, 4]的位置,它就不会起作用。 - Loc-Tran
@Loc-Tran 添加了一个assert语句。 - Rahn
插入的顺序不应该影响结果。你的解决方案对于list_b = ["b", "a", "c"]pos = [2, 0, 4]并不适用。它应该给出相同的结果,但实际上并没有。 - Jeyekomon

3

不使用列表推导式的一种方式:

>>> a = [0,1,2,3,4]
>>> b = ['a', 'b', 'c']
>>> ind = [0, 2, 4]
>>> d = dict(zip(ind, b))

>>> [t for k in [(d.get(i),j) for i,j in enumerate(a)] for t in k if t is not None]
['a', 0, 1, 'b', 2, 3, 'c', 4]

0

另一种选择是不使用索引累加器,但仍需要索引按升序排列。

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]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接