如果我有
l = ['a','b','x','f']
我想将'x'
替换为sub_list = ['c','d','e'
]
最好的方法是什么?我有,
l = l[:index_x] + sub_list + l[index_x+1:]
答案 0 :(得分:5)
l = ['a','b','x','f']
sub_list = ['c','d','e']
ind = l.index("x")
l[ind:ind+1] = sub_list
print(l)
['a', 'b', 'c', 'd', 'e', 'f']
如果您有一个包含多个x's
使用索引的列表,则会替换第一个x
。
如果您想要替换所有x's
:
l = ['a','b','x','f',"x"]
sub_list = ['c','d','e']
for ind, ele in enumerate(l): # use l[:] if the element to be replaced is in sub_list
if ele == "x":
l[ind:ind+1] = sub_list
print(l)
['a', 'b', 'c', 'd', 'e', 'f', 'c', 'd', 'e']
答案 1 :(得分:2)
您可以找到要替换的元素的索引,然后将子列表分配给原始列表的切片。
def replaceWithSublist(l, sub, elem):
index = l.index(elem)
l[index : index+1] = sub
return l
>>> l = ['a','b','x','f']
>>> sublist = ['c','d','e']
>>> replaceWithSublist(l, sublist, 'x')
['a', 'b', 'c', 'd', 'e', 'f']
答案 2 :(得分:1)
另一种方法是使用insert()
方法
l = ['a','b','x','f']
sub_list = ['c','d','e']
ind = l.index('x')
l.pop(ind)
for item in reversed(sub_list):
l.insert(ind, item)