首页 > 解决方案 > 通过条件从多维数组中仅获取一个子数组

问题描述

我有这个数组:

[
  {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]

标签: pythonpython-2.7

解决方案


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"获取 dict
  • 用于sorted按日期时间排序,然后使用索引

推荐阅读