python - 列表理解示例

标签 python list

如何使用列表理解来执行以下代码。我一直在看这些例子,但我无法弄清楚:|

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/

相关文章:

c# - 如何按自定义顺序对 list<string> 进行排序

c# - 如何在C#中对List <T>进行排序

python - 从变量取消引用内存中的 Python 列表对象时会发生什么?

c# - 比较多个列表的大小(计数)

python - 如果多个列上的条件, Pandas 数据框中的新列无法获得预期值基础

python - Cython并行循环问题

python - 什么是删除列表中双倍重复项但允许三元组/更大的 Pythonic 方法?

python - 为什么 QListView 在尝试检索文本时给我一个 NoneType ?

Python ctypes 和没有足够的参数(缺少 4 个字节)

python - 如何在 o(n) 时间内找到列表中字符相对于列表中其他字符的位置?