>>> a = ['1', '2', '3', '4'] >>> a ['1', '2', '3', '4'] >>> i = a.index('2') + 1 # after the item '2' >>> a[i:i] = ['2.4', '2.6'] >>> a ['1', '2', '2.4', '2.6', '3', '4'] >>>
您可以使用list.insert(i, x)
Python定义的单个元素轻松插入s[i:i] = [x]
.
a = ['1', '2', '3', '4'] for elem in reversed(['2.4', '2.6']): a.insert(a.index('2')+1, elem))
如果要插入列表,可以创建省略[]的函数:
def iextend(lst, i, x): lst[i:i] = x a = ['1', '2', '3', '4'] iextend(a, a.index('2')+1, ['2.4', '2.6'] # a = ['1', '2', '2.4', '2.6', '3', '4']