从元组列表中查找最小值

时间:2017-09-16 04:48:00

标签: python-3.x

我是编码新手,需要从元组列表中找到最小值。

def min_steps(step_records):
    """ random """
    if step_records != []:
        for steps in step_records:
            day, step = steps
            result = min(step)
    else:
        result = None
    return result 

这会导致错误:

  

'int'对象不可迭代

如果列表是这样的话,如何返回min

step_records = [('2010-01-01',1),
                ('2010-01-02',2),
                ('2010-01-03',3)]

1 个答案:

答案 0 :(得分:0)

tuples可以编入索引(请参阅:Accessing a value in a tuple that is in a list)。

使用它我们可以从这些索引创建一个列表并像你那样调用最小值:

def min_steps(step_records):
    """ random """
    if step_records:
        result = min([step[1] for step in step_records]) # min([1,2,3])
    else:
        result = None
    return result

step_records = [('2010-01-01',1),
                ('2010-01-02',2),
                ('2010-01-03',3)]

print(min_steps(step_records))

输出:

1