首页 > 解决方案 > 循环遍历它的索引会改变的动态列表

问题描述

所以我有循环问题。如果我有两个列表

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]

标签: python

解决方案


尝试使用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]

推荐阅读