以下是一个示例代码,演示如何按照子位置对文档进行排序。
def sort_by_subposition(documents):
sorted_documents = sorted(documents, key=lambda x: x['sub_position'])
return sorted_documents
# 示例文档
documents = [
{'name': 'doc1', 'sub_position': 2},
{'name': 'doc2', 'sub_position': 1},
{'name': 'doc3', 'sub_position': 3},
{'name': 'doc4', 'sub_position': 1},
{'name': 'doc5', 'sub_position': 2}
]
# 按子位置排序
sorted_documents = sort_by_subposition(documents)
# 打印排序结果
for doc in sorted_documents:
print(doc)
运行以上代码将得到如下输出:
{'name': 'doc2', 'sub_position': 1}
{'name': 'doc4', 'sub_position': 1}
{'name': 'doc1', 'sub_position': 2}
{'name': 'doc5', 'sub_position': 2}
{'name': 'doc3', 'sub_position': 3}
代码中的sort_by_subposition
函数接受一个文档列表作为输入,并使用sorted
函数进行排序。key=lambda x: x['sub_position']
指定了按照每个文档的sub_position
字段进行排序。最后,函数返回排序后的文档列表。
在示例中,我们使用了一个包含文档名称和子位置的示例文档列表。排序后,按照子位置从小到大的顺序打印出文档。