2017-03-01 73 views
-5

這裏排序列表是我的清單:通過ID

data_set = [['ID=j234hg\n'], ['Date=19 October 1969\n'], ['Title=Court Scene With Cardinal Richelieu\n'], ['ID=s4k5jk\n'], ['Date=8 December 1970\n'], ['Title=Crossing The Atlantic On A Tricycle\n'], ['ID=n4j6l3j\n'], ['Date=7 December 1972\n'], '[Title=Mr. Pither']] 

我想通過ID進行排序:這裏 是我的代碼:

for index,l in enumerate(data_set): 
    if 'ID=' == l[0][:1]: 
     data_set[index]="ID="+l[0][6:].sort() 
print('Sort by ID') 
print(data_set) 
print() 

代碼運行,但不排序

+4

您應該謹慎考慮您的數據結構! –

+0

並非所有人都是高級或中級 – Supernova

+0

您是否可以正確更新data_set。您想根據ID進行排序,但是您的data_set是包含列表以及字符串的列表 – Mayank

回答

1

考慮到每行的固定長度爲三項(即:ID,日期,標題),您可以先對輸入進行重新組合,然後進行排序。

rows = [ data_set[i:i+3] for i in range(0,len(data_set), 3)] 
print sum(sorted(rows, key = lambda r:r[0][0]), []) 

輸出:

[['ID=j234hg\n'], ['Date=19 October 1969\n'], ['Title=Court Scene With Cardinal Richelieu\n'], ['ID=n4j6l3j\n'], ['Date=7 December 1972\n'], ['Title=Mr. Pither'], ['ID=s4k5jk\n'], ['Date=8 December 1970\n'], ['Title=Crossing The Atlantic On A Tricycle\n']] 
-1

使用集合或字典來完成這類任務。隨着名單,你可以最終打印與字「ID」第一要素,但沒有相關的數據作爲標題,日期等

0

假設你data_set看起來是這樣的:

>>> data_set = [['ID=j234hg\n', 'Date=19 October 1969\n', 'Title=Court Scene With Cardinal Richelieu\n'], ['ID=s4k5jk\n', 'Date=8 December 1970\n', 'Title=Crossing The Atlantic On A Tricycle\n'], ['ID=n4j6l3j\n', 'Date=7 December 1972\n', 'Title=Mr. Pither']] 

嘗試

>>> res = sorted(data_set, key=lambda x: x[0]) 
>>> res 
[['ID=j234hg\n', 'Date=19 October 1969\n', 'Title=Court Scene With Cardinal Richelieu\n'], ['ID=n4j6l3j\n', 'Date=7 December 
1972\n', 'Title=Mr. Pither'], ['ID=s4k5jk\n', 'Date=8 December 1970\n', 'Title=Crossing The Atlantic On A Tricycle\n']] 
+0

輸出放置所有的日期,然後ID然後標題,讓我試着調整代碼 – Supernova