2014-11-06 98 views
0

,如果我有具有多个值

l = ['a','b','x','f'] 

我想以取代sub_list = ['c','d','e']

什么是做到这一点的最好办法'x'更换列表的元素?我有,

l = l[:index_x] + sub_list + l[index_x+1:] 

回答

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多个x's列表。

如果你想更换所有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'] 
+0

@tobias_k,没错感谢我错过了+1 – 2014-11-06 12:51:32

+0

正如旁白:你的循环,如果更换包含的元素可能会无限运行被替换,例如如果'sublist = ['c','x','e']' – 2014-11-06 13:03:31

+0

@tobias_k,那么我添加了一个注释来处理这种情况 – 2014-11-06 13:06:16

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'] 
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)