I have this:
list = ["0001.exr", "0003.exr", "0002.dpx", "0001.dpx", "0002.exr", "0003.dpx"]
list.sort()
for line in list:
print (line)
And it's returning this:
0001.dpx
0001.exr
0002.dpx
0002.exr
0003.dpx
0003.exr
How can I return this result? (in a nice simple way)
0001.dpx
0002.dpx
0003.dpx
0001.exr
0002.exr
0003.exr
Just use a key for .sort()
that puts what's after "."
as more important than what is before it:
list.sort(key=lambda l: "".join(reversed(l.split(".")))
You sort according to name, then use the OS library to get the extension and sort according to it (as a key):
list.sort()
list.sort(key=lambda list_item: os.path.splitext(list_item)[-1])
You could use the built in sorted()
function with a custom cmp
function called sort
:
l = ["0001.exr", "0003.exr", "0002.dpx", "0001.dpx", "0002.exr", "0003.dpx"]
def sort(a, b):
if 'dpx' in a and 'exr' in b:
return -1
if float(a.split('.')[0]) < float(b.split('.')[0]):
return -1
return 1
answer = sorted(l, cmp=sort)
print(answer)
Output
['0001.dpx', '0002.dpx', '0003.dpx', '0001.exr', '0002.exr', '0003.exr']
As an aside, you shouldn't mask the built-in list()
function by using list
as a variable name.
list = ["0001.exr", "0003.exr", "0002.dpx", "0001.dpx", "0002.exr", "0003.dpx"]
lst_tuple=[]
for item in list:
lst_tuple.append((item.split('.')[0],item.split('.')[1]))
print sorted(lst_tuple, key=lambda element: (element[1], element[0]))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.