python - 通过条件从多维数组中仅获取一个子数组
问题描述
我有这个数组:
[
{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"获取 dict- 用于
sorted
按日期时间排序,然后使用索引
推荐阅读
- javascript - 有没有办法阻止chrome使用javascript在chrome的下拉列表中显示建议?
- c++ - 使用make将一个目录下的所有cpp文件编译成自己的g++可执行文件
- python - 如何将随机项目从列表转换为字符串?
- c# - 如何在String C#中将单词或单词获取为char
- node.js - 你如何在 ramdaJS 中将数据操作到 Json
- sql - 如何将某个日期范围的 MS SQL 数据库数据复制到另一台计算机上的数据库中?
- .net-core - Update-Database 不会将迁移应用到数据库
- cassandra - 使用两个数据中心和 LOCAL_QUORUM 写入 Cassandra 时的同步延迟
- c++ - 回到八皇后。我想不通。(我错过了哪一部分?)
- robotframework - 如何从日历机器人框架中选择未来一天的日期