繁体   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