首页 > 解决方案 > 如何在一列Python中打印出具有最大值的CSV文件行

问题描述

目前我有这些数据:

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

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

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

标签: pythonpython-3.x

解决方案


您可以使用函数的 key 参数max来提供一个函数,该函数从每一行中提取您想要找到最大值的值(这里 3 对应于列宽,并转换为浮点数):

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

推荐阅读