如何使用列表解析执行以下代码。我一直在看这些例子,但我无法弄清楚:|
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)
答案 0 :(得分:1)
替换这个for循环并不是一个好主意,因为你正在进行带副作用的函数调用(当前正在打印)。您可以使用else子句来构造一个新的列表,这个列表会更高效(INSERT INTO @Dis ...
O(1)
与append()
O(n)
对于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
这一事实被视为{{1} }:
False