我有一个清单
lis = ["Cat","Dog","Tiger","Elephant","Donkey","Fox"]
说我重新分配某些元素
lis[0] = "Lion"
lis[3] = "Zebra"
现在我的名单是
lis = ["Lion","Dog","Tiger","Zebra","Donkey","Fox"]
现在我必须返回未更改的元素。如何循环遍历元素并忽略已更改的元素并返回未更改的元素?我的想法是保留某种类型的检查,以便它尽快点击检查条件,它忽略元素并继续前进。
注意 - 我需要这样做而不删除任何元素。
答案 0 :(得分:3)
您需要保留包含已修改元素索引的数据结构。然后,在循环时,然后检查项目的索引是否在该结构中。
理想情况下,您使用set
(用于快速成员资格测试)和enumerate
(用于遍历容器同时获取其索引):
changed = {0, 3} # after you modify the list
for index, elem in enumerate(list):
if index not in changed:
# do something with element that wasn't changed.
答案 1 :(得分:1)
@JimFasarakisHilliard已经为您提供了这个问题的潜在后端(+1),让我可以在潜在的前端找到一个完整的解决方案:
def track(index):
changed.add(index)
return index
changed = set()
my_list = ["Cat", "Dog", "Tiger", "Elephant", "Donkey", "Fox"]
my_list[track(0)] = "Lion"
my_list[track(3)] = "Zebra"
for index, element in enumerate(my_list):
if index not in changed:
print(element) # do something with element that wasn't changed.