python - 在字符串列表中的特定元素之前和之后插入一个元素

标签 python list iteration

是否可以在出现特定字符串时插入到列表中。 示例:

List=['north','south','east','west','south','united']

因此,每次出现字符串 'south' 时,列表都会在列表中的元素 south 之前插入一个项目 'canada'

Results
List=['north','canada','south','east','west','canada','south','united']

编辑:对于不够具体,我深表歉意。我需要它来寻找特定的字符。

List1=['north','<usa>23<\usa>','east','west','<usa>1942<\usa>','united']
Result=['north','canada', '<usa>23<\usa>','east','west','canada','<usa>1942<\usa>','united']

最佳答案

为了能够将列表中的元素放置在特定位置,您需要列表insert 函数。

<list>.insert(<position>, <value>)

例如,如果您有一个包含以下内容的列表:

a = [2, 4, 6, 8, 12]

并且想在列表中添加 10 但保持当前顺序,你可以这样做:

a.insert(4, 10)

并会得到:

[2, 4, 6, 8, 10, 12]

编辑

要在每个“南”之前插入:

for i in range(len(<list>)):
    if <list>[i] == 'south':
        <list>.insert(i, 'canada')

关于python - 在字符串列表中的特定元素之前和之后插入一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34142182/

相关文章:

java - 转换一个类相同的对象

c# - 当列表有新项目时引发事件?

dom - 每当 .data 用于返回的元素时,jquery .each 都会生成 'undefined'

java - 迭代除一个特定值外的所有列表的最佳方法

python - 迭代 xlsx 文件并删除 unicode python openpyxl

python - 为什么在 Django 中使用线程局部变量不好?

python - 如何修复找不到 sdist pip-*.tar.gz

python - Matplotlib 补丁与提供的参数不匹配。

python - pytest 获取当前测试文件的文件路径

c# - 使用列表时如何在 foreach 中使用 CheckBoxFor?