Skip to main content
 首页 » 编程设计

Python:如何查询对象列表

2025年05月04日13me-sa

假设我有这个对象列表:

listt = [{ 
      "CustomerId": "1", 
      "Date": "2017-02-02", 
      "Content": "AAAAAAAA", 
      "Type": 2 
    }, 
    { 
      "CustomerId": "2", 
      "Date": "2017-02-03", 
      "Content": "BBBBBBBB", 
      "Type": 1 
    }, 
    { 
      "CustomerId": "3", 
      "Date": "2017-02-01", 
      "Content": "CCCCCCCCC", 
      "Type": 1 
    }, 
    { 
      "CustomerId": "4", 
      "Date": "2017-02-12", 
      "Content": "DDDDDDDDDD", 
      "Type": 2 
    }, ] 

找到这些问题答案的最简洁方法是什么?

  1. Minimum Date where Type = 1.

=> 2017-02-1

  1. Select Content where Type = 2 and Date = (Minimum Date among all objects with Type = 2)

=> AAAAAAAA

我正在阅读有关利用 lambda 和过滤器的信息,但我无法取得任何进展。有人可以帮忙吗?

请您参考如下方法:

这些是基本的 Python 数据结构。我建议使用 comprehensions 而不是 map 和 filter。例如:

>>> listt = [{ 
...       "CustomerId": "1", 
...       "Date": "2017-02-02", 
...       "Content": "AAAAAAAA", 
...       "Type": 2 
...     }, 
...     { 
...       "CustomerId": "2", 
...       "Date": "2017-02-03", 
...       "Content": "BBBBBBBB", 
...       "Type": 1 
...     }, 
...     { 
...       "CustomerId": "3", 
...       "Date": "2017-02-01", 
...       "Content": "CCCCCCCCC", 
...       "Type": 1 
...     }, 
...     { 
...       "CustomerId": "4", 
...       "Date": "2017-02-12", 
...       "Content": "DDDDDDDDDD", 
...       "Type": 2 
...     }, ] 
>>> min(d['Date'] for d in listt if d['Type'] == 1) 
'2017-02-01' 
>>> 

或者,对于您的第二个查询:

>>> min_date = min(d['Date'] for d in listt if d['Type'] == 2) 
>>> [d['Content'] for d in listt if d['Date'] == min_date] 
['AAAAAAAA'] 
>>> 

尝试坚持理解结构使事情更具可读性,IMO,而不是使用 lambda,虽然,这也有它的位置,而且是一个风格问题。然而,列表推导一般来说比lambda 的等效map 更快。但是,map 使用内置函数可以更快。