简体   繁体   English

在 Python 中模拟像 Sqlite3 这样的元组排序

[英]Emulating a Tuple Sort like Sqlite3 in Python

I'm trying to sort a list of tuples where there are certain tuple indices that contain None.我正在尝试对包含 None 的某些元组索引的元组列表进行排序。 In this case, the tuples with None in a specific index location need to be given priority over the other non-None values in the list of tuples.在这种情况下,在特定索引位置具有 None 的元组需要优先于元组列表中的其他非 None 值。

So for example, if I have a list which looks like this:例如,如果我有一个如下所示的列表:

[
(3.4, 43, None),
(5345.6, 42, None),
(43.24, 25, None),
(323.4, 433, None),
(5.6, 42, None),
(4.4, 235, None),
(None, None, 'Hello'),
(5.6, None, None),
(None, 235, None),
]

And I want my final list to look like (basically doing a "SELECT * FROM table ORDER BY column1,column3;")我希望我的最终列表看起来像(基本上是做一个“SELECT * FROM table ORDER BY column1,column3;”)

[
(None, 235, None),
(None, None, 'Hello'),
(3.4, 43, None),
(4.4, 235, None),
(5.6, 42, None),
(5.6, None, None),
(43.24, 25, None),
(323.4, 433, None),
(5345.6, 42, None),
] 

As of right now, I'm currently using截至目前,我目前正在使用

sortedSelectedResult = sorted(selectedResult,key=itemgetter(*indexSortOrderList))

where indexSortOrderList is a list which has a list of the index order by which the list of tuples need to be sorted.其中 indexSortOrderList 是一个列表,其中包含需要对元组列表进行排序的索引顺序列表。 But in this method, Nones are randomly placed within the list.但是在这种方法中,Nones 随机放置在列表中。 My current result looks like this, where indexSortOrder = [0,2] (ie) sort by first column, then the third column:我当前的结果如下所示,其中 indexSortOrder = [0,2] (即)按第一列排序,然后按第三列排序:

[(3.4, 43, None),
 (5345.6, 42, None),
 (43.24, 25, None),
 (323.4, 433, None),
 (5.6, 42, None),
 (4.4, 235, None),
 (None, None, 'Hello'),
 (5.6, None, None),
 (None, 235, None)]

I tried looking into operator.itemgetter and modifying the function to apply to my use case, but I'm having trouble with that as well..我尝试查看 operator.itemgetter 并修改该函数以适用于我的用例,但我也遇到了问题..

You can add a custom key considering None as 0:您可以添加自定义键,将None视为 0:

sorted(lst, key=lambda x: (isinstance(x[0], str), x[0] or 0,  isinstance(x[2], str) or x[2] or 0))

Code :代码

lst = [
(3.4, 43, None),
(5345.6, 42, None),
(43.24, 25, None),
(323.4, 433, None),
(5.6, 42, None),
(4.4, 235, None),
(None, None, 'hello'),
(5.6, None, None),
(None, 235, None),
]

print(sorted(lst, key=lambda x: (isinstance(x[0], str), x[0] or 0,  isinstance(x[2], str) or x[2] or 0)))

# [(None, 235, None),
#  (None, None, 'hello'),
#  (3.4, 43, None),
#  (4.4, 235, None),
#  (5.6, 42, None),
#  (5.6, None, None),
#  (43.24, 25, None),
#  (323.4, 433, None),
#  (5345.6, 42, None)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM