Reputation:
from operator import itemgetter
file = open("testdata.txt","r")
filein = []
for row in file:
filein.append(row.strip("\n"))
results= []
for item in filein:
results.append(item.split(","))
counter=0
for item in results:
itemlength = len(item)
for i in range(1, itemlength):
item[i] = int(item[i])
item.append(max(results[counter][1:4]))
item.append((sum(results[counter][1:4]))/3)
counter=counter+1
results.sort()
print("\n")
print(sorted(results,key=itemgetter(5),reverse=True))
[['DF', 8, 6, 8, 8, 7.333333333333333], ['ED', 10, 4, 6, 10, 6.666666666666667], ['TH', 9, 4, 7, 9, 6.666666666666667], ['EK', 9, 4, 5, 9, 6.0]]
I have two questions. The first one is how can I print the first value (initials) with the 5th value [4], which is the highest score, in a new list? My second question how can I get the average score[5] of the three scores to 2 decimal places?
This task is for my assessment, I hope that you could help me out! Thank you
Upvotes: 1
Views: 94
Reputation: 180512
You can unpack and use str.format, {:.2f}
will format the average to two decimal places:
l = [['DF', 8, 6, 8, 8, 7.333333333333333], ['ED', 10, 4, 6, 10, 6.666666666666667],
['TH', 9, 4, 7, 9, 6.666666666666667], ['EK', 9, 4, 5, 9, 6.0]]
for ini, _, _, _, highest, avg in l:
print("Initials: {}, highest : {}, average: {:.2f}".format(ini, highest, avg))
Initials: DF, highest : 8, average: 7.33
Initials: ED, highest : 10, average: 6.67
Initials: TH, highest : 9, average: 6.67
Initials: EK, highest : 9, average: 6.00
Upvotes: 2
Reputation: 10223
Round decimal number:
Demo:
>>> round(1.7777, 2)
1.78
>>> round(1.7777, 0)
2.0
>>>
>>> "%.2f"%(1.239)
'1.23'
Use subscription to get value from th list.
Demo
>>> l = ["a", "b", "c", "d"]
>>> l[0] #- First item
'a'
>>> l[-1] #- Last item
'd'
>>> l[3] #- Last item i.e. Item from the index 3
'd'
>>>
code:
>>> l = [['DF', 8, 6, 8, 8, 7.333333333333333], ['ED', 10, 4, 6, 10, 6.666666666666667], ['TH', 9, 4, 7, 9, 6.666666666666667], ['EK', 9, 4, 5, 9, 6.0]]
>>> for i in l:... print "%s, %d, %.2f"%(i[0], i[4], i[5])
...
DF, 8, 7.33
ED, 10, 6.67
TH, 9, 6.67
EK, 9, 6.00
>>>
Upvotes: 1
Reputation: 2567
To get 1st and last elements in a new list
l = [['DF', 8, 6, 8, 8, 7.333333333333333], ['ED', 10, 4, 6, 10, 6.666666666666667], ['TH', 9, 4, 7, 9, 6.666666666666667], ['EK', 9, 4, 5, 9, 6.0]]
l2 = []
for i in l:
l2.append([i[0], i[-1]])
print l2
l2 = [['DF', 7.333333333333333], ['ED', 6.666666666666667], ['TH', 6.666666666666667], ['EK', 6.0]]
Upvotes: 0
Reputation: 49330
Just keep subscripting.
>>> mylist = [[1,2],[5,6]]
>>> mylist[0]
[1,2]
>>> mylist[0][1]
2
Upvotes: 0