Concatenating files in order

Erik python at lucidity.plus.com
Tue May 23 18:04:15 EDT 2017


On 23/05/17 22:14, Mahmood Naderan via Python-list wrote:
> sorted=[[int(name.split("_")[-1]), name] for name in files]

This isn't sorting anything. At no point do you invoke a sort operation.

It's processing the list in the original order and generating a new list 
with a different format but *in the same order*.

You should either call the sorted() built-in or invoke the list.sort() 
method on the list to cause a sort operation to be performed.

I suspect the reason why "it works" is because the filenames happen to 
be returned in a sorted order already when you tested it ...

Use the REPL to see what you are doing (and force an unsorted order to 
check that what you are doing works):

$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
 >>> files = ["foo_99", "foo_10", "foo_2", "foo_20"]
 >>> sorted_files=[[int(name.split("_")[-1]), name] for name in files]
 >>> files
['foo_99', 'foo_10', 'foo_2', 'foo_20']
 >>> sorted_files
[[99, 'foo_99'], [10, 'foo_10'], [2, 'foo_2'], [20, 'foo_20']]
 >>> sorted(sorted_files)
[[2, 'foo_2'], [10, 'foo_10'], [20, 'foo_20'], [99, 'foo_99']]
 >>> sorted_files
[[99, 'foo_99'], [10, 'foo_10'], [2, 'foo_2'], [20, 'foo_20']]
 >>> sorted_files.sort()
 >>> sorted_files
[[2, 'foo_2'], [10, 'foo_10'], [20, 'foo_20'], [99, 'foo_99']]

Regards,
E.



More information about the Python-list mailing list