按列表len排序列表

时间:2011-01-19 13:20:50

标签: python sorting

我正在尝试按len大小排序列表。但我得到一个奇怪的语法错误。我是python的新手,所以我可能做错了什么

代码的相关部分:

 orderedpaths=[]
 if(len(paths)==1):
  orderedpaths=paths
 else: 
  c=0
  while(len(paths)!=0):

   if(c==0):
    smallest=(len(paths[c])
    c+=1

   else:
    if(len[paths[c])<smallest):
     smallest=(len(paths[c]))
     orderedpaths.append(paths[c])
     del paths[c]
     c+=1    

 return orderedpaths

我得到的错误是:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.py", line 153
    c+=1
    ^
SyntaxError: invalid syntax

我不知道为什么。

3 个答案:

答案 0 :(得分:22)

您的问题是括号中的数字:

smallest=(len(paths[c])

并在:

if(len[paths[c])<smallest):

以及:

if(len[paths[c])<smallest):

要根据路径长度对路径进行排序,您可以尝试:

orderedpaths = sorted(paths, key=len)

以下是sorted的文档。

答案 1 :(得分:2)

eumiro's answer中所述,使用sorted()是可行的方法。

请注意,sorted()(以及list.sort(key=..))仅在Python 2.4中引入。如果你在我的船上并且必须使用&lt; 2.4,你可以创建自己的版本。粗略的例子:

import inspect
def my_sorted(in_list, key=lambda x:x):

    # basic error checking
    if not is_instance(in_list, list):
        raise ValueError("expecting 1st argument to be a list")

    if not inspect.isroutine(key):
        raise ValueError("key must be a function/method")

    # convert to [ (key(item1), item1), .... ]
    key_map = map(lambda x: (key(x),x), in_list)
    # standard sort, while effectively sort by key(item)
    key_map.sort()

    # convert back original format and return
    return [x for _,x in key_map]

然后您可以这样使用它:

orderedpaths = my_sorted(paths, key=len)

答案 2 :(得分:-1)

您也可以使用这段漂亮的代码:):

>>> a = [[1,2,3], [1,2,3,4], [1,2]]
>>> b = sorted(a, lambda x,y: 1 if len(x)>len(y) else -1 if len(x)<len(y) else 0)
>>> print b
[[1, 2], [1, 2, 3], [1, 2, 3, 4]]

如果您想要另一个排序顺序,请将-1与-1交换。

由于评论者注意到此代码仅适用于python 2.x. 有一些更漂亮的代码也适用于python 3.x:

>>> a = [[1,2,3], [1,2,3,4], [1,2]]
>>> b = sorted(a, key = len)
>>> print b
[[1, 2], [1, 2, 3], [1, 2, 3, 4]]
相关问题