如何在一列Python中打印出具有最大值的CSV文件行

时间:2018-12-04 13:01:20

标签: python python-3.x

当前我有以下数据:

EXAMPLE_DATA = [
['time', 'age', 'height', 'width', 'ethnicity', 'religion'],
['18:42:11', '61', '153.9615', '0.8', 'Mixed', 'None'],
['18:35:00', '34', '116.4253333', '10.17', 'Mixed', 'None'],
['14:25:40', '14', '119.7673475', '65.44', 'Mixed', 'None'],
['19:39:06', '33', '145.2423535', '9.4', 'Mixed', 'None'],
['17:22:17', '66', '122.2351111', '12.4', 'Mixed', 'None'],
['13:15:00', '77', '187.4983398', '19.88', 'Mixed', 'None']
]

这是我的代码:

headings = ['Time', 'Age', 'Height', 'Width', 'Ethnicity', 'Religion']
rows = [0, 1, 2, 3, 4, 5]

for heading, row in zip(headings, rows):
    print(heading + ': ' + datafunc[row])

'datafunc'根据要输出的数据行调用EXAMPLE_DATA [1]或EXAMPLE_DATA [2]或([3],[4]等)。 如果它调用EXAMPLE_DATA [1],这是我得到的输出:

Time: 18:42:11
Age: 61
Height: 153.9615
Width: 0.8
Ethnicity: Mixed
Religion: None

我想做的是编写代码,找到最大的“宽度”,然后不仅打印出最大的“宽度”,而且还打印出“时间”,“年龄”,“身高”, “种族”和“宗教”与最大的“宽度”在同一行数据中。

如果您需要更多信息,请告诉我。谢谢。

3 个答案:

答案 0 :(得分:7)

您可以使用max函数的key自变量来提供一个函数,该函数从每一行中提取要查找其最大值的值(此处3对应于列宽,我们将其转换为浮动):

max_row = max(EXAMPLE_DATA[1:], key=lambda row: float(row[3]))

答案 1 :(得分:0)

尝试一下:

find_max(data_list):
    max_row =0;
    max_width=0;
    for i in range(1,len(data_list)):
        if float(data_list[i][3]) > max_width:
            max_width = float(data_list[i][3])
            max_row = i
    return max_row

row_to_print = find_max(EXAMPLE_DATA)
list_to_print = EXAMPLE_DATA[row_to_print]

for i in range(len(headings):
    print(headings[i]+" : " + list_to_print[i])

答案 2 :(得分:0)

尝试一下:

EXAMPLE_DATA = [
['time', 'age', 'height', 'width', 'ethnicity', 'religion'],
['18:42:11', '61', '153.9615', '0.8', 'Mixed', 'None'],
['18:35:00', '34', '116.4253333', '10.17', 'Mixed', 'None'],
['14:25:40', '14', '119.7673475', '65.44', 'Mixed', 'None'],
['19:39:06', '33', '145.2423535', '9.4', 'Mixed', 'None'],
['17:22:17', '66', '122.2351111', '12.4', 'Mixed', 'None'],
['13:15:00', '77', '187.4983398', '19.88', 'Mixed', 'None']
]

headings = ['Time', 'Age', 'Height', 'Width', 'Ethnicity', 'Religion']
rows = max(EXAMPLE_DATA[1:], key=lambda e: float(e[3]))
print(rows)
for heading, row in zip(headings, rows):
    print(heading + ': ' + row)

输出:

C:\Users\Desktop>py x.py
['14:25:40', '14', '119.7673475', '65.44', 'Mixed', 'None']
Time: 14:25:40
Age: 14
Height: 119.7673475
Width: 65.44
Ethnicity: Mixed
Religion: None