Search code examples
pythonstringlistinteger

How to Rearrange Some Strings in a List and Find the Average of It's Integers?


For my class, I have to take a file and turn it into a list with lists inside of it separating each "contestant" and from there, rearrange the Strings in it to where if it were a name, the name John Doe would instead become Doe John. On top of this, I also have to take the integers in each list and calculate their average. We haven't done this in class which is why I'm so lost. Thank you for any help.

I've been able to turn my file into a list by doing what I've put below, but after that, I'm completely stuck.

my_file = open("sample-1.txt.txt")
data3 = my_file.read()
list1 = data3.split(" ")
flist = list()
len_flist = 10
for i in range(0, len(list1), len_flist):
    flist.append(list1[i:i+len_flist])
my_file.close()
print(flist)

Output:

[['Ty', 'Cobb', '13099', '11434', '3053', '724', '295', '117', '1249', '9'], ['\nChipper', 'Jones', '10614', '8984', '1671', '549', '38', '468', '1512', '1'], ['\nJonny', 'Bench', '8674', '7658', '1254', '381', '24', '389', '891', '1'], ['\nHank', 'Aaron', '13941', '12364', '2294', '624', '98', '755', '1402', '3'], ['\nTony', 'Gwynn', '10232', '9288', '2378', '543', '85', '135', '434', '2'], ['\nJohn', 'Smoltz', '1167', '948', '118', '26', '2', '5', '79', '3'], ['\nAaron', 'Woods', '1122', '123', '324', '45', '88', '1561', '9', '18']]

The output is how my teacher wants us to write it. But I'm not sure how to flip the names to be "Cobb, Ty," and then calculate the average of the numbers. The way she wants the output to be by the end is "[[Cobb, Ty, 3747.5], [...], [...]}"


Solution

  • It is better if you use file.readlines() instead of file.read(), because it splits it into each line, separating each contestant.

    With that, you can do stuff with each contestant, like so:

    fin = open("sample-1.txt.txt")
    contestants = fin.readlines()
    final = []
    for contestant_string in contestants:
        if contestant_string == "\n":
            continue #if there is an extra line at the end, with nothing in it
        contestant = contestant_string.strip().split(" ") #remove any annoying "\n"s
        data = [contestant[1], contestant[0]] # reverses name
        total = 0 # holds total score
        for score in contestant[2:]: # goes through each score (skips the name)
            total+=int(score)
        data.append(total/len(contestant[2:]) # the average
        final.append(data)
    fin.close()
    print(data)