Python:如何查询对象列表?

时间:2017-02-03 19:55:30

标签: python list dictionary

假设我有这个对象列表:

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. Type = 1的最短日期。
  2.         

    => 2017年2月1日

         
        
    1. 选择Type = 2和Date =(Type = 2的所有对象中的最小日期)
    2. 的内容         

      => AAAAAAAA

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

3 个答案:

答案 0 :(得分:7)

这些是基本的Python数据结构。而不是mapfilter我建议使用 comprehensions 。 E.g:

>>> 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,尽管它也有它的位置,而且是风格问题。但是,列表推导通常比使用map的等效lambda更快。但是,使用内置函数map可以更快。

答案 1 :(得分:1)

要查找type = 1的最小日期,您可以首先过滤type = 1上的列表,然后将过滤后的列表传递给min函数(密钥为lambda x: x['Date']以查找元素最少'日期') as:

#                        performs `min` operation on `'Date'` v
>>> min([d for d in listt if d['Type'] ==1], key=lambda x: x['Date'])
{'CustomerId': '3', 'Type': 1, 'Content': 'CCCCCCCCC', 'Date': '2017-02-01'}

这是dict对象,列表中的Date最小。我们假设它存储为变量my_dict。要查找日期,请执行以下操作:

my_dict['Date']

要查找与其关联的内容,请执行以下操作:

my_dict['Content']

注意:要查找Type=2的内容,请在d['Type'] ==1声明中将d['Type'] ==2替换为min

答案 2 :(得分:0)

这是一个具有理解力的版本。对于第一个问题:

minval = min(elem['CustomerId'] for elem in listt if elem['Type']==1)
print(minval)

对于第二个版本,您可能不希望首先搜索最小值,然后将每个元素与最小值进行比较,因为这需要遍历列表两次。相反,最好搜索最小值并跟踪其索引。使用enumerate函数

可以很容易地理解这一点
minval, index = min((elem['CustomerId'], _) 
                    for _, elem in enumerate(listt) if elem['Type']==2)
print(minval, listt[index])
相关问题