如何在列表中选择一个项目,然后在

2024-04-25 12:39:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用列表中的另一项替换列表中的一项(具体地说,就是后面的项)。我目前无法找到一个程序来执行这项任务,虽然。你知道吗


Tags: 程序列表
3条回答

只需使用索引切换:

your_list[i], your_list[i + 1] = your_list[i + 1], your_list[i]

如果你有索引的话

l = [1,2,3,4,5] 
index = # get the index of the item 
l[index], l[index - 1] = l[index - 1], l[index] 

如果您想修改iterable(您的列表),那么应该使用copy:slice表示法[:]。你知道吗

my_list = ['(', 'E']
for i, item in enumerate(my_list[:]):
    if item == '(':
        # replace it with the item next to it
        my_list[i] = my_list[i+1]

您还应该使用tryexcept块来捕获最终的KeyError,以防您要查找的项目是列表中的最后一个。你知道吗

相关问题 更多 >