首页 > 解决方案 > 如何在 python 中比较和打印二维列表中的元素?

问题描述

我有这个 2D 列表,其中第一个元素是公司的名称,第二个元素是高级开发人员的薪水,第三个元素是他们每周工作的小时数。

brands = [["Microsoft", "120", "38", "1124"], ["Apple", "150", "40", "1800"], ["Google", "110", "35", "1437"]]

我正在尝试比较brands[0][1] with brand[1][1] and brands [2][1]和打印行业中的最低和最高工资,例如"The lowest wage: Google, 110" "The highest wage: Apple,150",然后打印最低和最高工作时间,对于一个简短的列表,使用 if 和 else 语句很容易,但我正在尝试制作一个通用循环,以防万一更大的列表。

我尝试了 min() 但它没有成功,我相信有办法让它工作。

标签: pythonlistloopsmaxmin

解决方案


我会对你的列表进行排序,然后取第一个和最后一个元素。您可以将其放入f-string用于打印(如果使用 python 3.6 或更高版本):

sorted_brands = sorted(brands, key=lambda x: int(x[1]))

print(f'the lowest wage: {sorted_brands[0][0]}, {sorted_brands[0][1]}, the highest wage: {sorted_brands[-1][0]}, {sorted_brands[-1][1]}')
#'the lowest wage: Google, 110, the highest wage: Apple, 150'

推荐阅读