2017-02-03 75 views
1

比方說,我有對象名單:Python:如何查詢對象列表?

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

=> 2017年2月1日

  • 選擇內容其中Type = 2和日期= (與第一類型的所有對象中最小日期= 2)
  • => AAAAAAAA

    我在閱讀關於利用lambda和過濾器,但我一直無法取得任何進展。任何人都可以幫忙嗎?

    +0

    你在db上還是僅僅在列表中有這些對象?如果他們在db中,你可以使用ORM進行查詢,這將更容易和更有效地檢索。 –

    +0

    數據庫中沒有它們。 :( – 90abyss

    回答

    7

    這些是基本的Python數據結構。我建議使用理解而不是mapfilter。例如:

    >>> 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'] 
    >>> 
    

    儘量堅持修真結構使事情變得更易讀,海事組織,而不是使用lambda,雖然,也有它的地方,是而是一個風格問題。然而,列表理解在總體上更快比等效maplambda更快。但是,使用內置函數,map可以更快。

    +0

    簡單,清晰,美觀... –

    +0

    但是它遍歷了兩次我發現並不優雅的列表,通過使用枚舉函數可以找到最小值和內容,只有一個列表遍歷 - 參見下面 –

    +0

    @AndiKleve是的,的確,最好是簡單地返回整個詞典並在那裏查詢最後一個鍵 –

    1

    用於查找與類型= 1的最小日期,則可以首先篩選的類型= 1的列表,然後通過過濾列表以min功能(帶有密鑰作爲lambda x: x['Date']找到具有最小「日期」元素)作爲:

    #      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'} 
    

    這是具有在列表中的最小一個Date對象dict。假設它被存儲爲變量my_dict。爲了找到爲止,做:

    my_dict['Date'] 
    

    爲了找到與之相關的內容,這樣做:

    my_dict['Content'] 
    

    注:對於發現的Type=2的內容,以及在d['Type'] ==2更換d['Type'] ==1min聲明。

    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]) 
    
    +0

    我將規範解釋爲「返回所有內容」,而不僅僅是與最小值對應的內容。在這種情況下,無論如何都需要雙程。 –

    +0

    @ juanpa.arivillaga:同意 - 根據這個解釋,我也會使用兩遍。 –