python - 循环遍历它的索引会改变的动态列表
问题描述
所以我有循环问题。如果我有两个列表
list1 = [1, 2, 3]
list2 = [4, 5, 6]
我将遍历它们并删除元素并将其附加到另一个列表中,这样我的列表将是
list1 = [1, 2, 3, 4, 5]
list2 = [6]
或列表可以是字符串 <
现在当我循环时如何:
for i in range(len(list2))
我知道我的程序会弹出IndexError: list index out of range
是否有任何方法可以有效地循环而不退出两个列表(比如检查两者)
而不使用任何库,如 itertools 等。
示例代码:
for i in range(len(list1)):
if(list1[i] > list2[i]):
list1.append(list2[i])
del list2[i]
else:
list2.append(list1[i])
del list1[i]
解决方案
尝试使用copy.deepcopy()
可变列表(如list
)
仅将 [:] 用于不可变列表(如int
)
编辑
list1 = ['p', 'p2', 'p3']
list2 = ['p4', 'p5', 'p6']
for item in list2[:]:
if item != 'p6':
list1.append(item)
list2 = list2[1:]
顺便说一句,如果你只想连接这两个列表,你可以简单地运行list1.extend(list2)
编辑 2 您的代码中的内容不是您提出的问题。只需添加一些 if 语句:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
for i in range(len(list1)):
if len(list1) > i and len(list2) > i:
if list1[i] > list2[i]:
list1.append(list2[i])
del list2[i]
else:
list2.append(list1[i])
del list1[i]
else:
# print('out of range. skipping') # or raise exception or break
continue
# [2]
# [4, 5, 6, 1, 3]
推荐阅读
- odoo-11 - 如何调用 Odoo v11 的特定电子邮件通知
- mysql - 当插入失败并且在 Spring Boot JPA 中为空时如何回滚训练?
- matplotlib - Matplotlib 错误:“str”对象没有属性“get_figure”
- reactjs - 警告:validateDOMNesting(...): 不能作为子级出现
- python - 查找每行的前 3 个值并将值保存在 Pandas 中
- sum - Sum across multiple columns by row (in Stata)
- android - 相机在android 10中返回黑色图像
- python - Python十进制问题
- django - Django - 在多个字段上注释并加载相关对象
- visual-studio-code - pytorch无法在vscode中解析和自动完成