【问题标题】:Finding smallest number at specific column and then returning that row在特定列查找最小数字,然后返回该行
【发布时间】:2020-09-09 20:09:31
【问题描述】:

如果我有表数据 = [[1, 2, 0.5], [2, 5, 0.49]] 。我如何创建一个函数,在两行中找到第三列的最小元素,然后返回该数字所在的行?

例如。因为第三列中的最小数字是两行中的 0.49。我希望函数返回[2, 5, 0.49]

【问题讨论】:

    标签: python list


    【解决方案1】:

    使用min() functionkey 比较列表的第三个元素。

    min(data, key=lambda l: l[2])
    

    【讨论】:

    • 领先我一秒 :)
    【解决方案2】:

    这样怎么样:

    td = [[1, 2, 0.5], [2, 5, 0.49]]
    
    col = 2 # third column
    
    min_row = td[0] # initialze to something
    for row in td:
        if row[col] < min_row[col]:
            min_row = row
    
    print(min_row)
    

    【讨论】:

      猜你喜欢
      • 2012-09-16
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 2023-03-30
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多