Nested List Sorting

# Nested List sort


L = [['IT', 56], ['CSE', 53], ['EEE', 52], ['ECE', 55]]


# Sorting a nested List using bubble sort

# default - sorts by first element of nested list


for i in range(0,len(L)):

for j in range(0,len(L)-1):

if(L[j]>L[j+1]):

L[j],L[j+1]=L[j+1],L[j]


print("Sort by first element (default)")

print(L)


# Sorting a nested List using bubble sort

# Sort by second element of nested list


for i in range(0,len(L)):

for j in range(0,len(L)-1):

if(L[j][1]>L[j+1][1]):

L[j],L[j+1]=L[j+1],L[j]

print("Sort by Second element")

print(L)


"""

Sample output

 >python NestedListSort.py


Sort by first element (default)


[['CSE', 53], ['ECE', 55], ['EEE', 52], ['IT', 56]]


Sort by Second element


[['EEE', 52], ['CSE', 53], ['ECE', 55], ['IT', 56]]


"""

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu