Supernova Supernova -4 years ago 99
Python Question

Sorting a List by ID

here is my list:

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']]


I want to sort by ID:
here is my code:

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()


the code runs but does not sort

Answer Source

Considering that each row has fixed length of three items (ie: ID, Date, Title), you can first regroup input and then sort.

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]), [])

output:

[['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']]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download