python列表删除功能的问题

时间:2020-03-09 04:21:37

标签: python python-3.x

我知道这可能是一个重复的问题。但是由于我的英语表达不佳,我不知道如何搜索。

最近我在python list.remove中发现一个问题,这是代码:

data = []
for i in range(1000):
    Tempdict = {}
    Tempdict["code"] = str(i)
    data.append(Tempdict)

codes_to_keep = ("1","8","80")
for i in data:
    if not i["code"] in codes_to_keep:
        data.remove(i)

print(data) #{"code":"1","code":"3","code":"5".......},it will keep odd number leave.

或者如果我使用它删除需要删除的号码:

data = []
for i in range(1000):
    Tempdict = {}
    Tempdict["code"] = str(i)
    data.append(Tempdict)

codes_to_delete = ("1","8","80")
for i in data:
    if i["code"] in codes_to_delete:
        data.remove(i)

print(data) #{"code":"0","code":"2"xxx},This is what I expected 

发生了什么事?

1 个答案:

答案 0 :(得分:0)

要获得正确答案,

data = []
for i in range(1000):
    Tempdict = {}
    Tempdict["code"] = str(i)
    data.append(Tempdict)


codes_to_keep = ("1","8","80")
# for i in data:
#     if not i["code"] in codes_to_keep:
#         data.remove(i)

data = list(item for item in data if item["code"] in codes_to_keep)

print(data)
[{'code': '1'}, {'code': '8'}, {'code': '80'}]