简体   繁体   中英

How to print all columns and rows from a csv file's min and max value in python

I have to print out the min/max values from a specific column, which I was able to do. But I also need to show the data from all the columns of the min/max fields.

below is the code:

import csv

with open('phone_data.csv','r') as p_data:
data = csv.reader(p_data, delimiter=',')
next(data)
d_col = list(data)

minTemp = min([float(elem[2]) for elem in d_col])
maxTemp = max([float(elem[2]) for elem in d_col])
print("min value is: ", minTemp)
print("max value is: ", maxTemp)

You should sort the rows (stored in d_col ) with the third item as the key instead:

import csv

with open('phone_data.csv','r') as p_data:
    data = csv.reader(p_data, delimiter=',')
    next(data)
    d_col = list(data)

min_row = min(d_col, key=lambda row: float(row[2]))
max_row = max(d_col, key=lambda row: float(row[2]))
print("min row is: ", min_row)
print("max row is: ", max_row)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM