出现特定字符串时是否可以插入列表。例子:
List=['north','south','east','west','south','united']
Run Code Online (Sandbox Code Playgroud)
因此,每次出现字符串 'south' 时,列表都会在列表中'canada'的元素 south 之前插入一个项目。
Results
List=['north','canada','south','east','west','canada','south','united']
Run Code Online (Sandbox Code Playgroud)
编辑:我很抱歉不够具体。我需要它来寻找特定的字符。
List1=['north','<usa>23<\usa>','east','west','<usa>1942<\usa>','united']
Result=['north','canada', '<usa>23<\usa>','east','west','canada','<usa>1942<\usa>','united']
Run Code Online (Sandbox Code Playgroud)
小智 9
在另一个元素之前插入元素
>>> x = [1,2,3,4,5]
>>> x.insert(x.index(4), 22)
>>> x
[1, 2, 3, 22, 4, 5]
Run Code Online (Sandbox Code Playgroud)
在另一个元素之后插入元素
>>> x = [1,2,3,4,5]
>>> x.insert(x.index(3)+1, 22)
>>> x
[1, 2, 3, 22, 4, 5]
Run Code Online (Sandbox Code Playgroud)
但是,这不适用于多次插入
>>> x = [1,2,3,4,5,4,6,4,7]
>>> x.insert(x.index(4), 22)
>>> x
[1, 2, 3, 22, 4, 5, 4, 6, 4, 7]
Run Code Online (Sandbox Code Playgroud)
为了能够将列表中的元素放置在特定位置,您需要 listinsert功能。
<list>.insert(<position>, <value>)
Run Code Online (Sandbox Code Playgroud)
例如,如果您有一个包含以下内容的列表:
a = [2, 4, 6, 8, 12]
Run Code Online (Sandbox Code Playgroud)
并且想要在列表中添加 10 但保持当前顺序,您可以执行以下操作:
a.insert(4, 10)
Run Code Online (Sandbox Code Playgroud)
并将获得:
[2, 4, 6, 8, 10, 12]
Run Code Online (Sandbox Code Playgroud)
编辑
要在每个“南”之前插入,请执行以下操作:
for i in range(len(<list>)):
if <list>[i] == 'south':
<list>.insert(i, 'canada')
Run Code Online (Sandbox Code Playgroud)
简单的回答:
def blame_canada(old_list):
new_list = []
for each in old_list:
if each == 'south':
new_list.append('canada')
new_list.append(each)
return new_list
Run Code Online (Sandbox Code Playgroud)