2024-04-25 12:39:01 发布
网友
我想用列表中的另一项替换列表中的一项(具体地说,就是后面的项)。我目前无法找到一个程序来执行这项任务,虽然。你知道吗
只需使用索引切换:
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,以防您要查找的项目是列表中的最后一个。你知道吗
try
except
KeyError
只需使用索引切换:
如果你有索引的话
如果您想修改iterable(您的列表),那么应该使用copy:slice表示法
[:]
。你知道吗您还应该使用
try
except
块来捕获最终的KeyError
,以防您要查找的项目是列表中的最后一个。你知道吗相关问题 更多 >
编程相关推荐