Python 3 Rearranging Tuples with priority

137 views Asked by At

This program is written with the intent of collecting Name,Age and Score using commas as delimiters. After values have been keyed in, the program will rearrange the list giving priority to Name, Age and Score respectively. However, the result has not been as expected.

from operator import itemgetter, attrgetter
store=[] 
store1=[]
while True: 
    block = input("Enter Name, Age, Score: ") 
    if block: 
       store.append(block) 
    else: 
       break
store1=tuple(store)
print(sorted(store1, key=itemgetter(0,1,2)))

Result:

Enter Name, Age, Score: John,50,100
Enter Name, Age, Score: Jan,40,50
Enter Name, Age, Score: John,38,10
Enter Name, Age, Score: 
['Jan,40,50', 'John,50,100', 'John,38,10']

As shown above, there is no problem in rearranging the name. In fact, the problem lies in the 2nd and 3rd variables when being sorted. The function itemgetter does not seem to work.

1

There are 1 answers

2
wookiekim On

You take the input name, age, score as variable block:

block = input("Enter Name, Age, Score: ")

and you append the block as a whole to the list.

store.append(block)

This way, the entire string containing the name, age and score is considered to be one entry. Since the name appears first in the string, it only appears as if the sorting is done for the name only.

store1=tuple(store) looks unnecessary as well. Here is my how you can achieve what you want using list of tuples instead of tuple of strings :

from operator import itemgetter, attrgetter
store=[]

while True:
  block = input("Enter Name, Age, Score: ")
  if block:
    entry = tuple(block.split(',')[:3])
    store.append(entry)
  else:
    break
print(sorted(store, key=itemgetter(0,1,2)))