I am somewhat new to Python...
我对Python有些新意见......
I have an array of dicts that I got by reading a file containing JSON messages, i.e. using something like this:
我通过读取包含JSON消息的文件获得了一系列的dicts,即使用以下内容:
import json
ws = []
with open('messages.txt', 'r') as f:
for line in f:
data = json.loads(line)
ws.append(data)
Each JSON message has, among other things, three fields: "date" and "type" and "location". I need to sort the array first by date, then by type within each block of identical dates, then by location within each block of identical types. How can I do that? Thx much!
除其他外,每个JSON消息都有三个字段:“日期”和“类型”和“位置”。我需要先按日期排序数组,然后按相同日期的每个块中的类型排序,然后按相同类型的每个块中的位置排序。我怎样才能做到这一点?太多了!
1 个解决方案
#1
9
ws.sort(key=lambda datum: (datum['date'], datum['type'], datum['location']))
Tuples are sorted naturally first by first element, then by succeeding elements.
元组首先由第一个元素自然排序,然后由后续元素自然排序。
#1
9
ws.sort(key=lambda datum: (datum['date'], datum['type'], datum['location']))
Tuples are sorted naturally first by first element, then by succeeding elements.
元组首先由第一个元素自然排序,然后由后续元素自然排序。