0

thank you for your interest, but i couldn't with this.

in PYTHON 3 , for example, i have a list.

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 , the folders, for example; have this pattern : '1. Introducción','2. Conceptos Básicos de Desarrollo Web' ...... ''9. Tipos de Input','10. Área de Texto',

it's not reading like the windows explorer

sorting example that i need

Mike Brian Olivera
  • 1,414
  • 1
  • 16
  • 21
  • What's your problem? That it's only listing directories, or that it's doing an alphabetical sort rather than parsing out the numbers from each directory name and sorting based on those? – user3553031 Jul 05 '14 at 20:34

4 Answers4

2

sort your list with a lambda:

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

int(x.split(".")[0]) is the directory number so in '1. Introducción' it would be 1 and so on..

Or sort in-place Lista.sort(Lista,key=lambda x: int(x.split(".")[0]))

sorted creates a new list list.sort sorts the original list

A link to the docs that explains the difference between list.sort and sorted

Taken from the docs:

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

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

Lambda expressions (sometimes called lambda forms) are used to create anonymous functions. The expression lambda arguments: expression yields a function object. The unnamed object behaves like a function object defined with

def <lambda>(arguments):
    return expression

A simple example:

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
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • this was the answer more complete and works a great. But i dont understand good the second code. could you send me a link to understand please. THANK YOU A LOT =) – Mike Brian Olivera Jul 05 '14 at 21:00
  • You're welcome, the lambda or the sort method? – Padraic Cunningham Jul 05 '14 at 21:05
  • yes, i have never seen something like that. or what is lambda. thanks =) – Mike Brian Olivera Jul 05 '14 at 21:06
  • I will add a link to both. – Padraic Cunningham Jul 05 '14 at 21:07
  • thank you =) i will be waiting – Mike Brian Olivera Jul 05 '14 at 21:14
  • @MikeBrian, if you have any other questions feel free to ask, there is a good explanation in the docs about using keys to sort. – Padraic Cunningham Jul 05 '14 at 21:18
  • This will raise `ValueError` if there is no int conversion in the lambda... – dawg Jul 05 '14 at 22:02
  • @dawg what do you mean, the directory string starts with a number? – Padraic Cunningham Jul 05 '14 at 22:04
  • @PadraicCunningham: What happens when there is a file/directory WITHOUT the number? It is an easy fix to handle that case. – dawg Jul 05 '14 at 22:06
  • @dawg Well as far as I understood all the directories are numbered but feel free to add whatever you want. – Padraic Cunningham Jul 05 '14 at 22:07
  • @dawg, I can add an if/else but that would not sort the list and therefore defeat the purpose, what is the alternative? – Padraic Cunningham Jul 05 '14 at 22:14
  • @PadraicCunningham: `sorted(Lista, key=lambda field: [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', field)])` if you want a lambda or put that same bit into a key function more rationally... `def kf(field): return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', field)]` – dawg Jul 05 '14 at 22:25
  • I was thinking `sorted(l,key = lambda x: int(x.split(".")[0]) if x.split(".")[0].isdigit() else x)` – Padraic Cunningham Jul 05 '14 at 22:35
  • What if there is no `"."` in the string? Don't think that a sort should sort no matter what you feed it? ;-) – dawg Jul 05 '14 at 23:30
  • @dawg if there is no number in the string neither mine nor yours will sort it ;) – Padraic Cunningham Jul 05 '14 at 23:33
  • @PadraicCunningham: `if there is no number in the string neither mine nor yours will sort it` That is not true. The sort I provided A) will not raise a value error without a number; B) Will sort on the found numbers in correct sequence; C) The sorts correctly strings with NO numbers lexicographically; D) is [widely tested as the correct way](http://blog.codinghorror.com/sorting-for-humans-natural-sort-order/) to do natural sorting. Try it. – dawg Jul 05 '14 at 23:54
  • @dawg I did, if a string happens to be missing a number then it ends up at the back of the list which is exactly what happens in my if/else. – Padraic Cunningham Jul 06 '14 at 00:04
  • @PadraicCunningham: Try with `['00001 items', '01 items', '1 item', '2 items', '9 items', '23 items', 'an item', 'item 01', 'item 1', 'item 99', 'items']` Excel, Windows Explorer, OS X, and the sort I gave you all sort in exactly that order of the list (with integers -- not float values). That is your target (ok, slight modification to the sort I gave you. Use: `sorted(Lista, key=lambda field: [(int(s), s) if s.isdigit() else s for s in re.split(r'(\d+)', field)])` so the integers with leading '0' is handled the same... – dawg Jul 06 '14 at 00:20
2

Assuming that each item in your list starts with a number followed by a dot-character, you can sort your list like this (where lst is the original list):

>>> 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']
timgeb
  • 76,762
  • 20
  • 123
  • 145
1

I'm using this snippet for sorting normally

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 )

It changes the list itself:

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']
pandita
  • 4,739
  • 6
  • 29
  • 51
-1

This is just because Windows Explorer sorts things alphabetically. If you want it to sort differently, try adding a space in front of the names you want to go first.