PYTHON: Simplest way to open a csv file and find the maximum number in a column and the name assosciated with it?

后端 未结 1 722
一向
一向 2020-12-04 03:29

I have looked at this reference so please do not refer me to it.

Find max number in .CSV file in Python I struggled to modify this code to my own document for over

相关标签:
1条回答
  • 2020-12-04 04:08

    The max function should handle that for you. In my below code I've already "read" the CSV (with fake data, but you seem to have a grasp on that portion)

    data = [
        ["California", 123456],
        ["Idaho", 123],
        ["Utah", 2]
    ]
    
    print max(data, key=lambda _: _[1])
    

    This yields ['California', 123456]

    The key=lambda _: _[1] tells the function to use the second value of each record, the population in this case, to check the maximum.

    Putting it all together should be something like:

    def largestState():
        INPUT = "statepopulations.csv"
        COLUMN = 5
        with open(INPUT, "rU") as csvFile:
            data = csv.reader(csvFile)
            next(data, None)
        return max(data, key=lambda _: _[COLUMN])
    
    0 讨论(0)
提交回复
热议问题