簡體   English   中英

從多維數組僅按條件獲取一個子數組

[英]Get from a multimensional array only one sub-array by conditions

我有這個數組:

[
  {u'createdAt': datetime.datetime(2018, 8, 1, 12, 3, 41), u'rawValue': -200.0, u'data_type': 's'}, 
  {u'createdAt': datetime.datetime(2018, 8, 1, 11, 58), u'rawValue': -200.0, u'data_type': 's'}, 
  {u'createdAt': datetime.datetime(2018, 8, 1, 11, 56, 51), u'rawValue': -200.0, u'data_type': 'm'}
 ]

我只想獲得一個與2個條件相對應的子數組:

1 : createdAt is bigger

2 : data_type = s

通過使用某些庫可以做到這一點嗎?

我試圖這樣:

dataToReturn = []

    for data in datas:
        if date_type in data['data_type']:
            dataToReturn.append(data['data_type'])
    return dataToReturn

但是似乎不是更好的主意。

預期產量:

['createdAt' : datetime.datetime(2018, 8, 1, 12, 3, 41), 'rawValue' : -200.0]
import datetime

d = [
  {u'createdAt': datetime.datetime(2018, 8, 1, 12, 3, 41), u'rawValue': -200.0, u'data_type': 's'}, 
  {u'createdAt': datetime.datetime(2018, 8, 1, 11, 58), u'rawValue': -200.0, u'data_type': 's'}, 
  {u'createdAt': datetime.datetime(2018, 8, 1, 11, 56, 51), u'rawValue': -200.0, u'data_type': 'm'}
 ]

value = [i for i in d if i["data_type"] == "s"]
res = sorted(value, key=lambda x: x["createdAt"], reverse=True)
print(res[0])
print(len(value))

輸出:

{u'data_type': 's', u'rawValue': -200.0, u'createdAt': datetime.datetime(2018, 8, 1, 12, 3, 41)}
2
  • [i for i in d if i["data_type"] == "s"]以使用data_type ==“ s”來獲取字典
  • 使用sorted按日期時間排序,然后使用index

您可以使用max查找具有最大createdAt時間的子數組

>>> import datetime
>>> lst = [{u'data_type': 's', u'rawValue': -200.0, u'createdAt': datetime.datetime(2018, 8, 1, 12, 3, 41)}, {u'data_type': 's', u'rawValue': -200.0, u'createdAt': datetime.datetime(2018, 8, 1, 11, 58)}, {u'data_type': 'm', u'rawValue': -200.0, u'createdAt': datetime.datetime(2018, 8, 1, 11, 56, 51)}]
>>> {str(k):v for k,v in max(filter(lambda x: x['data_type'] == 's', lst), key=lambda x: x['createdAt']).items() if str(k) in ['createdAt', 'rawValue']}
{'rawValue': -200.0, 'createdAt': datetime.datetime(2018, 8, 1, 12, 3, 41)}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM