【问题标题】:a way to sorting in python [duplicate]一种在python中排序的方法[重复]
【发布时间】:2014-07-05 20:28:47
【问题描述】:

感谢您的关注,但我不能。

例如,在 PYTHON 3 中,我有一个列表。

import os
list = []
for carpeta in os.listdir(os.getcwd()):
 if(os.path.isdir(carpeta)):
     LISTA.append(carpeta)
print(LISTA)
~
$THIS IT PRINTS JUST THE DIRECTORIES:
['1. Introducción', '10. Área de Texto', '11. Listas de Selección', '12. Estructura de Archivo HTML', '13. Estructura del Proyecto', '14. Incluir CSS', '15. Selecciones con CSS', '16. reset.css', '17. Box Model', '18. Elementos flotantes', '19. Anchos Máximos y Mínimos', '2. Conceptos Básicos de Desarrollo Web', '20. Centrado Horizontal', '21. Imagen de Fondo', '22. Fuentes con Formato', '23. Formateando Listas', '24. Formateando Tablas', '25. Resumen', '3. Títulos y Párrafos', '4. Enlaces', '5. Imágenes', '6. Listas', '7. Tablas', '8. Formularios', '9. Tipos de Input']

BUT ,例如文件夹;有这个模式:'1。介绍','2。 Conceptos Básicos de Desarrollo Web' ......''9.输入提示','10。 Área de Texto',

它不像 Windows 资源管理器那样阅读

【问题讨论】:

  • 你有什么问题?它只是列出目录,还是按字母顺序排序而不是从每个目录名称中解析出数字并根据这些进行排序?

标签: python sorting python-3.x operating-system


【解决方案1】:

使用 lambda 对列表进行排序:

sorted(Lista,key=lambda x: int(x.split(".")[0]))

int(x.split(".")[0]) 是目录号码,所以在'1. Introducción' 中它将是1 等等..

或就地排序Lista.sort(Lista,key=lambda x: int(x.split(".")[0]))

sorted 创建一个新列表 list.sort 对原始列表进行排序

link 致解释 list.sort 和 sorted 之间区别的文档

取自docs

lambda_expr ::= "lambda" [parameter_list]: expression

lambda_expr_nocond ::= "lambda" [parameter_list]: expression_nocond

Lambda 表达式(有时称为 lambda 形式)用于创建匿名函数。表达式 lambda arguments: expression 产生一个函数对象。未命名对象的行为类似于使用

定义的函数对象
def <lambda>(arguments):
    return expression

一个简单的例子:

lam = lambda x : x + 4

def foo(x):
    return x+4

print("Calling foo: {}".format(foo(5)))
print("Calling lam: {}".format(lam(5)))
Calling foo: 9
Calling lam: 9

【讨论】:

  • 这是更完整的答案并且效果很好。但我不明白第二个代码。你能给我一个链接来理解吗?非常感谢 =)
  • 不客气,是 lambda 还是 sort 方法?
  • 是的,我从未见过这样的事情。或者什么是 lambda。谢谢 =)
  • 我将添加两个链接。
  • 谢谢 =) 我会等着的
【解决方案2】:

假设列表中的每个项目都以数字开头,后跟一个点字符,您可以像这样对列表进行排序(其中lst 是原始列表):

>>> lst.sort(key=lambda x:int(x.split()[0][:-1]))
>>> lst
['1. Introducci\xc3\xb3n', '2. Conceptos B\xc3\xa1sicos de Desarrollo Web', '3. T\xc3\xadtulos y P\xc3\xa1rrafos', '4. Enlaces', '5. Im\xc3\xa1genes', '6. Listas', '7. Tablas', '8. Formularios', '9. Tipos de Input', '10. \xc3\x81rea de Texto', '11. Listas de Selecci\xc3\xb3n', '12. Estructura de Archivo HTML', '13. Estructura del Proyecto', '14. Incluir CSS', '15. Selecciones con CSS', '16. reset.css', '17. Box Model', '18. Elementos flotantes', '19. Anchos M\xc3\xa1ximos y M\xc3\xadnimos', '20. Centrado Horizontal', '21. Imagen de Fondo', '22. Fuentes con Formato', '23. Formateando Listas', '24. Formateando Tablas', '25. Resumen']

【讨论】:

    【解决方案3】:

    我正在使用这个 sn-p 进行正常排序

    def sort_nicely( l ):
        """ Sort the given list in the way that humans expect.
    
        Source: http://stackoverflow.com/a/5491962
        """
        convert = lambda text: int(text) if text.isdigit() else text
        alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
        l.sort( key=alphanum_key )
    

    它会改变列表本身:

    import re
    
    stuff = ['1.Intro','11. Look at me','2. Chapter 2']
    sort_nicely(stuff)
    
    In[12]: stuff
    Out[12]: ['1.Intro', '2. Chapter 2', '11. Look at me']
    

    【讨论】:

      【解决方案4】:

      这只是因为 Windows 资源管理器按字母顺序排序。如果您希望它以不同的方式排序,请尝试在您想排在第一位的名称前添加一个空格。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-02-04
        • 1970-01-01
        • 2014-02-28
        • 1970-01-01
        • 1970-01-01
        • 2015-10-27
        • 2021-02-04
        • 2011-08-06
        相关资源
        最近更新 更多