0
#Name,Scores
a,6
b,8
c,2
k,23
d,18
r,13
w,4
h,9

The code should print the Name and Scores of the top 3 bands in order (starting with top, to bottom).

The code should then print the Name and Scores of the bottom 3 bands in order (starting with bottom, to top).

How do I do this?

Thank you in advance.

Daniel
  • 63
  • 5

4 Answers4

1

You should make them variables and store the values into the variables, then use a while True: line and add a line that compares one variable with another, then use print() to print all the top 3 first then print() the bottom 3.

1

Something like this:

with open ('data.txt') as f:
  lines = [l.strip() for l in f.readlines()]
  lines = [tuple(l.split(',')) for l in lines]
  lines.sort(key=lambda tup: int(tup[1]))
  print(lines[:3])
  lines[-3:].reverse()
  print(lines[-3:])

where data.txt is

a,6
b,8
c,2
k,23
d,18
r,13
w,4
h,9
balderman
  • 22,927
  • 7
  • 34
  • 52
1

You Can use list of tuples and use slicing to obtain the results

lt = [('a',6),
('b',8),
('c',2),
('k',23),
('d',18),
('r',13),
('w',4),
('h',9)]

print(lt[:3]) #for first three
print(lt[-3:]) #for last three
Krishna Singhal
  • 631
  • 6
  • 9
0

convert it into dictionary, then sort the dictionary and then print top and bottom bands.

team = {'a': 6, 'b': 8, 'c': 2, 'k': 23, 'd': 18, 'r': 13, 'w': 4, 'h': 9}

team = sorted(team.items(), key =
             lambda kv:(kv[1], kv[0]), reverse=True)
print(team)
print("Top 3 Bands")
print(team[:3])
print("Bottom 3 Bands")
print(team[-3:])

Output