Skip to main content
 首页 » 编程设计

python之按列表 len 排序列表列表

2025年05月04日12itcoder

我正在尝试按 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 

我不知道为什么。

请您参考如下方法:

您的问题是括号的数量:

smallest=(len(paths[c]) 

并在:

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

还有:

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

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

orderedpaths = sorted(paths, key=len) 

这是 sorted 的文档.