这是我的清单:
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()
代码运行但不排序
答案 0 :(得分: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 :(得分: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']]
答案 2 :(得分:-1)
将集或字典用于此类任务。使用列表,您最终可以打印为带有“ID”字样的第一个元素,但没有相关数据作为标题,日期等。