Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.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
Python 按字母顺序排列二维列表_Python - Fatal编程技术网

Python 按字母顺序排列二维列表

Python 按字母顺序排列二维列表,python,Python,我有一个很长的2d列表,其中包含以下形式的字符串 [[Month, Item, Price],[Month, Item, Price],.......]] 我按字母顺序排列的伪短版本2d列表是 msl =[['March', 'cook', '4.53'], ['March', 'book', '3.23'], ['June', 'clothes', '1.52'], ['December', 'clothes', '3.42']] 我试图做的是编写代码,而不使用字典或lambda来按项目的

我有一个很长的2d列表,其中包含以下形式的字符串

[[Month, Item, Price],[Month, Item, Price],.......]]
我按字母顺序排列的伪短版本2d列表是

msl =[['March', 'cook', '4.53'], ['March', 'book', '3.23'], ['June', 'clothes', '1.52'], ['December', 'clothes', '3.42']]
我试图做的是编写代码,而不使用字典或lambda来按项目的字母顺序对项目进行排序。例如,它不再是[['March'、'cook'、'4.53']、['March'、'book'、'3.23'],而是变成了[['March'、'book'、'3.23']、['March'、'cook'、'4.53']…],但是我写的代码似乎不起作用,我也不知道为什么。我写了以下内容

if msl[h][0] == msl[h+1][0] : # If month is the same as next month
    print "true"
    size = len( msl )         # start an item dictionary sort(msl[i][1])
    unsorted = True
    while unsorted :
        unsorted = False
        i = 0
        while i < size-1 :
            if msl[i][1] > d[i+1][1] : #if the item is greater than the next
                print "true again"
                temp = d[i]            # temp = current sublist
                d[i] = d[i+1]          # current sublist becomes next sublist
                d[i+1] = temp          # next sublist becomes current sublist
                unsorted = True
                i = i + 1

else :
    h= h+1

我在那里写了trues来检查程序的进程在哪里,它对所有的程序都是真的,但是当我试图打印出新的msl时,什么都没有出来。是否可以编写类似于在月份保持不变的情况下,使用.sort方法对项目进行排序,将其应用于项目索引,但重新调整整个子列表的大小?

我无法理解该代码,因为在您显示的任何地方都没有定义引用的d[…]

在任何情况下,您似乎正在编写冒泡排序,这对于一个非常长的列表来说是一个非常糟糕的主意-这是已知的最不有效的排序方法之一。按照@Arrieta的建议,将内置排序与lambda或itemgetter一起使用是最好的选择

但不需要使用key=参数进行排序。这很正常;-通常可以使用更旧、更浪费的DSU装饰、排序、非装饰图案:

>>> decorated = [(x[1], x) for x in msl]
>>> decorated.sort()
>>> msl[:] = [x[1] for x in decorated]
>>> msl
[['March', 'book', '3.23'], ['December', 'clothes', '3.42'],
 ['June', 'clothes', '1.52'], ['March', 'cook', '4.53']]
这是通过构建一个包含两个元组的新列表来装饰原始列表的,其中每个元组的第一个元素是排序键,第二个元素是原始列表的项。然后是普通的那种。然后撕下装饰物。最后的msl[:]还将使用排序列表替换原始列表的全部内容

顺序如下:

>>> msl = [(x[1], x) for x in msl]
>>> msl.sort()
>>> msl = [x[1] for x in msl]

是另一种方法,但是通过创建一个新的列表对象,列表对象msl将被绑定到更改中-它不会使用msl[:]=。。。拼写。

我能想出一种使用lambdas的方法。有什么特别的原因不想使用它吗?它可以归结为sortedML,key=operator.itemgetter1注意,您需要导入operator。我想知道您不使用lambdas的限制是否也适用于operator.itemgetter。请注意,如图所示,它将返回一个新的排序列表。如果要对列表进行适当排序,只需编写msl.sortkey=operator.itemgetter1。使用列表列表而不是对象列表有什么特殊原因吗?随着需求的变化,前者往往有点脆弱。