2016-06-07 80 views
0

我被要求定義一個基於文件擴展名排序列表的函數。如何按每個元素中的特定字符對列表進行排序?

我理解排序,但我不明白如何從「。」開始排序。字符。

我想以下結果:

>>> extsort(['a.c', 'a.py', 'b.py', 'bar.txt', 'foo.txt', 'x.c']) 
['a.c', 'x.c', 'a.py', 'b.py', 'bar.txt', 'foo.txt'] 
+0

讀了關於'key'參數 –

+0

看看排序並提供一個分析和反轉文件名和擴展名lambda函數所以用file.ext回報分機開始。lambda中的.file。這適用於John Coleman的產品。 'l = ['x.c','a.py','b.py','bar.txt','foo.txt','a.c']' – LhasaDad

回答

4

您可以通過按鍵功能的參數sorted

>>> l = ['a.c', 'a.py', 'b.py', 'bar.txt', 'foo.txt', 'x.c'] 
>>> sorted(l, key=lambda x: splitext('.')[1]) 
['a.c', 'a.py', 'b.py', 'bar.txt', 'foo.txt', 'x.c'] 

如果您需要的文件用相同的擴展由他們的名字來排序您可以更改按鍵功能以反轉分割結果:

>>> l = ['x.c', 'a.py', 'b.py', 'bar.txt', 'foo.txt', 'a.c'] 
>>> sorted(l, key=lambda x: splitext(x)[::-1]) 
['a.c', 'x.c', 'a.py', 'b.py', 'bar.txt', 'foo.txt'] 
+0

',我想你的解決方案不是對。輸出是'['x.c','a.c','a.py','b.py','bar.txt','foo.txt']',我想thr作者想''[ 'a.c','x.c','a.py','b.py','bar.txt','foo.txt']'。 – BlackMamba

+0

好的我只看到一個問題。[1]在lambda函數末尾指定了什麼? – Este

+0

@BlackMamba嗯,可能。 OP沒有指定*給定擴展名內的值*是否必須進行排序。 – SethMMorton

3

對於解決方案即使某些文件沒有擴展名(並且有些更自我記錄),也可以使用os.path.splitext作爲sortedkey函數的一部分。當沒有文件擴展名,它將把擴展爲空字符串,'',所有其他擴展之前,分類整理:

>>> l = ['b.py', 'a.c', 'a.py', 'bar.txt', 'foo.txt', 'x.c', 'foo'] 
>>> sorted(l, key=lambda x: os.path.splitext(x)[1]) 
['foo', 'a.c', 'x.c', 'b.py', 'a.py', 'bar.txt', 'foo.txt'] 

注意b.pya.py前整理在這裏,因爲它第一次出現在輸入端,該排序僅在文件擴展名上鍵入。要按擴展名進行排序,然後輸入全名,鍵入擴展名的元組後面跟非擴展名(可通過使用[::-1]os.path.splitext進行分段返回值來輕鬆完成),因此a.py先於b.py無論他們出現在輸入其中:

>>> sorted(l, key=lambda x: os.path.splitext(x)[::-1]) 
['foo', 'a.c', 'x.c', 'a.py', 'b.py', 'bar.txt', 'foo.txt'] 
相關問題