Search code examples
pythonliststatisticsvar

How do I take data from multiple lists that are all inside a single variable in python and find out the mean mode and frequency


I'm making a blackjack game that requires me to calculate the scores at the end of multiple blackjack games such as what your cards added up to at the end of the games and find out the mean, mode and frequency. I've gotten the data laid out in a spread sheet but can't figure out how to read and add the score from the separate games since they're all being added together into one variable

import csv

with open("nathan_project_data.csv", "r") as f:
    reader = csv.reader(f)
    a = list(reader)
print(a)

with the output being: [['win', '21'], ['Hit', 'Stand', 'Loss', '17'], ['Hit', 'Stand', 'Loss', '18'], ['Stand', 'Loss', '18'], ['Stand', 'win', '19']]


Solution

  • Index -1 is the index of the last item in a list

    import csv
    
    with open("nathan_project_data.csv", "r") as f:
        reader = csv.reader(f)
        a = list(reader)
    print(a)
    
    scores = [] #create list to hold all the scores
    
    for item in a: #Loop through each item (lists) in the list
        scores.append(item[-1]) #Append (add) the last element of each item to 
                                #scores list
    
    print(scores) #prints [21, 17, 18, 18, 19]
    
    
    #Get Frequency of each score:
    frequency = {} #Dictionary to hold frequencies
    for score in scores:
       # checking the element in dictionary
       if score in frequency:
          # incrementing the count
          frequency[score] += 1
       else:
          # initializing the count
          frequency[score] = 1
    
    mean = sum(scores)/len(scores)
    
    #Do whatever other calcs you need