Python—仅当列表中存在某个特定元素时,才将元素插入列表
我有一个字符串列表Python—仅当列表中存在某个特定元素时,才将元素插入列表,python,python-3.x,list,Python,Python 3.x,List,我有一个字符串列表a,我想将我的列表与特定字符串b进行比较,如果在列表的某些元素中找到该字符串,我想在列表a前面插入另一个元素 因此,如果我说b='alice',我想对照b检查整个列表,如果任何元素是'alice',我想在'alice'前面添加'amber' 比如说: a = ['tom', 'alice'. 'chris'] 如果'alice'位于a中,则在'alice'之前插入'amber' 最终将是: a = ['tom', 'amber', 'alice'. 'chris'] 这是
a
,我想将我的列表与特定字符串b
进行比较,如果在列表的某些元素中找到该字符串,我想在列表a
前面插入另一个元素
因此,如果我说b='alice'
,我想对照b
检查整个列表,如果任何元素是'alice'
,我想在'alice'
前面添加'amber'
比如说:
a = ['tom', 'alice'. 'chris']
如果'alice'
位于a
中,则在'alice'之前插入'amber'
最终将是:
a = ['tom', 'amber', 'alice'. 'chris']
这是一种方法
Ex:
from itertools import chain
a = ['tom', 'alice', 'chris', 'alice', 'alice']
c = 'alice'
result = list(chain.from_iterable([['amber', i] if i == c else [i] for i in a]))
print(result)
['tom', 'amber', 'alice', 'chris', 'amber', 'alice', 'amber', 'alice']
输出:
from itertools import chain
a = ['tom', 'alice', 'chris', 'alice', 'alice']
c = 'alice'
result = list(chain.from_iterable([['amber', i] if i == c else [i] for i in a]))
print(result)
['tom', 'amber', 'alice', 'chris', 'amber', 'alice', 'amber', 'alice']
输出:
['tom', 'amber', 'alice', 'chris']
这将创建一个新列表。如果愿意,请将a重命名为新列表
a = ['tom', 'alice', 'chris', 'alice', 'alice', 'bill']
b = 'alice'
to_add = 'amber'
result = []
for i in a:
if i == b:
result.append(to_add)
result.append(i)
这使得:
>>> result
['tom', 'amber', 'alice', 'chris', 'amber', 'alice', 'amber', 'alice', 'bill']
>>>
除了“alice”中向后的'a',还有什么阻止您将伪代码转换为解决方案?这只会捕获“alice”的第一个实例。不清楚,但我认为OP说可能会有更多。是的,肯定会有更多的实例,很抱歉不清楚。@Vesper所以请不要接受我的答案,在这里使用其他的一个。