python - 如何在 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() 但它没有成功,我相信有办法让它工作。
解决方案
我会对你的列表进行排序,然后取第一个和最后一个元素。您可以将其放入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'
推荐阅读
- java - TensorFlow 2.0 和 Java API
- d3.js - 数据过滤器适用于 json 数据,但不适用于 csv 数据
- javascript - 从 Angular 中的 Click 事件处理程序获取源元素
- php - 在 Docker 中安装 GD 扩展
- php - 如何在 DateInterval 扩展类中创建 days 属性?
- python - 向数据框中添加新列,显示包含数字的所有行的总和
- python - 如何创建每另一列的前一行为1时增加1的ID
- php - 使用 ip 和掩码获取网络地址。(php, IPv6)
- java - javax.persistence.PersistenceException: org.hibernate.TransactionException: 已经有一个关联的托管连接
- c# - 如何减少代码中的 SQL 查询量?