如何使用列表理解来执行以下代码。我一直在看这些例子,但我无法弄清楚:|
Python: Removing list element while iterating over list
list_dicts = [{'site': 'living', 'status': 'ready' }, {'site': 'keg',
'status': 'ready' }, {'site': 'box', 'status': 'ready' }, {'site': 'wine',
'status': 'not_ready' }]
def call_some_func(m_site_dict):
print "I executed the 'call_something_function'"
for site in list_dicts[:]:
if site['status'] == 'ready':
call_some_func(site)
list_dicts.remove(site)
最佳答案
替换这个 for 循环并不是一个好主意,因为您正在进行具有副作用的函数调用(当前正在打印)。您可以使用 else 子句构造一个新列表,这会提高性能(append()
的 O(1)
与 O(n)
code> 表示 del
),例如:
In []:
new_list_dicts = []
for site in list_dicts:
if site['status'] == 'ready':
call_some_func(site)
else:
new_list_dicts.append(site)
new_list_dicts
Out[]:
I executed the 'call_something_function'
I executed the 'call_something_function'
I executed the 'call_something_function'
[{'site': 'wine', 'status': 'not_ready'}]
作为演示(但形式非常糟糕),您可以将其作为列表理解来执行,但它依赖于短路,并且 call_some_func()
返回 None
这被认为False
:
In []:
[site for site in list_dicts if site['status'] == 'ready' and
call_some_func(site) or site['status'] != 'ready']
Out[]:
I executed the 'call_something_function'
I executed the 'call_something_function'
I executed the 'call_something_function'
[{'site': 'wine', 'status': 'not_ready'}]
关于python - 列表理解示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46125882/