我有一个列表["a","b","c","a"]
,其中我想用"a"
替换["a_1","b_1","c_1"]
,使列表变成["a_1","b_1","c_1","b","c", "a_1","b_1","c_1"]
在python中最快的方法是什么?
答案 0 :(得分:3)
您可以对chain.from_iterable
和三元语句使用理解:
from itertools import chain
L = list('abca') # ['a', 'b', 'c', 'a']
rep_key, rep_val = ('a', ['a_1', 'b_1', 'c_1'])
res = list(chain.from_iterable([i] if i != rep_key else rep_val for i in L))
['a_1', 'b_1', 'c_1', 'b', 'c', 'a_1', 'b_1', 'c_1']
答案 1 :(得分:1)
如果要变异您的列表,则可以依靠切片。实际上,这会替换您列表中的元素,而不创建一个新元素。
lst = ["a", "b", "c", "a"]
a_indices = [i for i, c in enumerate(lst) if c == "a"]
for i in reversed(a_indices):
lst[i:i+1] = ['a_1', 'b_1', 'c_1']
print(lst) # ['a_1', 'b_1', 'c_1', 'b', 'c', 'a_1', 'b_1', 'c_1']
答案 2 :(得分:0)
使用简单的for循环:
l = ["a", "b", "c", "a"]
for i in range(len(l)):
if l[i] == "a":
l[i] = "a_1"
l+=["b_1", "c_1"]
>>> l
['a_1', 'b', 'c', 'a_1', 'b_1', 'c_1', 'b_1', 'c_1']
>>>
答案 3 :(得分:0)
简单的列表理解应该可以解决问题。
abc = ["a","b","c","a"]
# Method 1 by using for loop
new_abc = []
for i in abc:
if i == "a":
new_abc += ["a_1","b_1","c_1"]
else:
new_abc.append(i)
# Method 2 by list comprehension
another_abc = [("a_1","b_1","c_1") if i == "a" else i for i in abc]
another_abc = [i for x in another_abc for i in x] #flatten the list
print (new_abc)
print (another_abc)
结果:
['a_1', 'b_1', 'c_1', 'b', 'c', 'a_1', 'b_1', 'c_1']
['a_1', 'b_1', 'c_1', 'b', 'c', 'a_1', 'b_1', 'c_1']
答案 4 :(得分:0)
这是一个简单的生成器函数的好地方:
def lazy_replace(L, char, val):
for item in L:
if item == char:
yield from val
else:
yield item
>>> L = list('abca')
>>> val = ['a_1', 'b_1', 'c_1']
>>> list(lazy_replace(L, 'a', val))
['a_1', 'b_1', 'c_1', 'b', 'c', 'a_1', 'b_1', 'c_1']