用多个值替换列表的元素

yay*_*ayu 0 python

如果我有

l = ['a','b','x','f']
Run Code Online (Sandbox Code Playgroud)

我想替换'x'sub_list = ['c','d','e']

做这个的最好方式是什么?我有,

l = l[:index_x] + sub_list + l[index_x+1:]
Run Code Online (Sandbox Code Playgroud)

Pad*_*ham 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']
Run Code Online (Sandbox Code Playgroud)

如果你有一个列表,有多个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']
Run Code Online (Sandbox Code Playgroud)