Finding Min and Max of list generated from CSV file Python

后端 未结 1 1196
轮回少年
轮回少年 2021-01-26 02:42

I am trying to find the MIN and MAX values for each row of a CSV file and append them to the next position in the list, positions 5 and 6. I have managed to calculate the averag

1条回答
  •  再見小時候
    2021-01-26 03:22

    import csv
    
    sample  = open("sampleData.txt", "r")
    csv1 = csv.reader(sample, delimiter = ',')
    
    sorted_list = []
    
    for line in csv1:
        print '-- ORIG:', line
        tmp = sorted( [int(i) for i in line[1:]], reverse=True )  # eg: [99,78,56]
        stat_list = [round(sum(tmp)/float(len(tmp)), 2), min(tmp), max(tmp)]
        sorted_list.append( [line[0]] + tmp + stat_list )
    
    for s in sorted_list: print '** NEW: ', s # has ['Fred',99,78,56,78.0,57,99]
    

    You can use/modify the quick & dirty solution above. Note:

    1. The result is a list of lists with digits converted to integers.
    2. The float() is needed for computing average - just doing it on the denominator is enough for the whole result to be a float.
    3. List comprehensions are great shortcuts and efficient for avoiding for loops.
    4. The numpy module has builtin mean() function (among many others) that are useful and fast, especially for large arrays.

    OUTPUT (space added)

    • ORIG: ['Fred', '57', '78', '99']
    • ORIG: ['Wilma', '96', '4', '105']
    • ORIG: ['Bar', '23', '88', '65']

    • NEW: ['Fred', 99, 78, 57, 78.0, 57, 99]

    • NEW: ['Wilma', 105, 96, 4, 68.33, 4, 105]
    • NEW: ['Bar', 88, 65, 23, 58.67, 23, 88]

    0 讨论(0)
提交回复
热议问题