Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List Python如何在特定条件下对列表进行排序_List_Python 2.7_Sorting - Fatal编程技术网

List Python如何在特定条件下对列表进行排序

List Python如何在特定条件下对列表进行排序,list,python-2.7,sorting,List,Python 2.7,Sorting,我有一个列表列表,我想按字母顺序按4个索引对列表进行排序,但有些情况下它将是无或空的,所以这些情况需要在底部 为进一步澄清,应按AaBbCc进行排序,然后选择“无”或“空”(如果可以)。我只希望第一批货能按实际情况订购 from operator import itemgetter list_of_list = [[0,1,2,3,'Ab'],[0,1,2,3,'bA'],[0,1,2,3,' '],[0,1,2,3,'None'], [0,1,2,3,''],[0,1,2,3,'Ca']

我有一个列表列表,我想按字母顺序按4个索引对列表进行排序,但有些情况下它将是无或空的,所以这些情况需要在底部

为进一步澄清,应按AaBbCc进行排序,然后选择“无”或“空”(如果可以)。我只希望第一批货能按实际情况订购

from   operator import itemgetter
list_of_list = [[0,1,2,3,'Ab'],[0,1,2,3,'bA'],[0,1,2,3,' '],[0,1,2,3,'None'], [0,1,2,3,''],[0,1,2,3,'Ca'] ]

list_of_list = sorted(list_of_list, key=itemgetter(4))

print list_of_list

Output: [[0, 1, 2, 3, ''], [0, 1, 2, 3, ' '], [0, 1, 2, 3, 'Ab'], [0, 1, 2, 3, 'Ca'], [0, 1, 2, 3, 'None'], [0, 1, 2, 3, 'bA']]
应按如下方式输出:

[[0, 1, 2, 3, 'Ab'], [0, 1, 2, 3, 'bA'],[0, 1, 2, 3, 'Ca'], [0, 1, 2, 3, 'None'], [0, 1, 2, 3, ''], [0, 1, 2, 3, ' ']]
您可以尝试以下方法:

>>> list_of_list = [[0, 1, 2, 3, 'Ab'],
                    [0, 1, 2, 3, 'bA'],
                    [0, 1, 2, 3, ' '],
                    [0, 1, 2, 3, None],
                    [0, 1, 2, 3, ''],
                    [0, 1, 2, 3, 'Ca']]
>>> list_of_list = sorted(list_of_list,
                          key=lambda x: x[4] if isinstance(x[4], basestring) else "",
                          reverse=True)
>>> print list_of_list
[[0, 1, 2, 3, 'bA'], [0, 1, 2, 3, 'Ca'], [0, 1, 2, 3, 'Ab'], [0, 1, 2, 3, ' '], [0, 1, 2, 3, None], [0, 1, 2, 3, '']]
如果第四个元素是字符串,则使用它作为排序键,否则将使用空字符串作为比较键

或者,您可以将列表拆分为两个列表,只对第一个列表进行排序,然后像下面这样附加其余元素:

list_of_list = sorted(x
                      for x in list_of_list
                      if isinstance(x[4], basestring) and len(x[4].strip())) + \
               [x
                for x in list_of_list
                if not isinstance(x[4], basestring) or not len(x[4].strip())]
print list_of_list
屈服

[[0, 1, 2, 3, 'Ab'], [0, 1, 2, 3, 'Ca'], [0, 1, 2, 3, 'bA'], [0, 1, 2, 3, ' '], [0, 1, 2, 3, None], [0, 1, 2, 3, '']]

现在还不完全清楚您是否需要遵循其他排序标准,这个解决方案也不完全完美,但至少它将字符串排序在前面,将其余的放在后面。

我在排序标准中添加了更多内容。基本上只是让字母先按字母顺序排列,然后再按字母顺序排列。是不是“None”的意思是“None”(无引号?)的意思是“None”(无),两者都是——意思相同。因此,要么是表示None的字符串,要么是实际的关键字None。它们应该放在底部。您可以使用
(isinstance(x[4],basestring)和x[4]!=“None”)
来避免
None
字符串。