我在下面有这个词典的示例列表。我想知道为什么下面的代码只会循环遍历列表中的两个值?为什么它不循环遍历列表中的每个值?
updated_list_of_site_dicts = [{'site': 'living', 'status': 'ready' }, {'site': 'keg', 'status': 'ready' }, {'site': 'box', 'status': 'ready' }, {'site': 'wine', 'status': 'ready' }]
for site_dict in updated_list_of_site_dicts:
if site_dict['status'] == 'ready':
print site_dict['site'] + " is ready"
updated_list_of_site_dicts.remove(site_dict)
print updated_list_of_site_dicts
答案 0 :(得分:1)
使用list comprehension来更新:
updated_list_of_site_dicts = [d for d in updated_list_of_site_dicts
if d['status'] != 'ready']
请注意,在您当前的示例中,您已全部“准备就绪”,因此您将获得一个空列表。这是一个状态尚未就绪的示例:
updated_list_of_site_dicts = [{'site': 'living', 'status': 'ready' },
{'site': 'keg', 'status': 'ready' },
{'site': 'box', 'status': 'ready' },
{'site': 'wine', 'status': 'NOT READY' }]
for d in updated_list_of_site_dicts:
if d['status'] == 'ready':
print(d['site'] + " is ready")
living is ready
keg is ready
box is ready
updated_list_of_site_dicts = [d for d in updated_list_of_site_dicts
if d['status'] != 'ready']
print(updated_list_of_site_dicts)
[{'site': 'wine', 'status': 'NOT READY'}]
答案 1 :(得分:1)
它只循环两次因为remove()方法导致列表索引移位。
如果要循环列表并删除元素,则应按相反的顺序迭代列表。如;
updated_list_of_site_dicts = [{'site': 'living', 'status': 'ready' }, {'site': 'keg', 'status': 'ready' }, {'site': 'box', 'status': 'ready' }, {'site': 'wine', 'status': 'ready' }]
for i in range(len(updated_list_of_site_dicts) - 1, -1, -1):
site_dict = updated_list_of_site_dicts[i]
if site_dict['status'] == 'ready':
print site_dict['site'] + " is ready"
updated_list_of_site_dicts.remove(site_dict)
print updated_list_of_site_dicts
此外,如果您只想删除元素,也可以使用过滤器。
>>> updated_list_of_site_dicts = [{'site': 'living', 'status': 'ready' }, {'site': 'keg', 'status': 'ready' }, {'site': 'box', 'status': 'ready' }, {'site': 'wine', 'status': 'ready' }, {'site': 'can', 'status': 'not_ready' }]
>>> updated_list_of_site_dicts = filter(lambda x: x['status'] != 'ready', updated_list_of_site_dicts)
>>> updated_list_of_site_dicts
[{'status': 'not_ready', 'site': 'can'}]