Python解释if key(arg)<键(ANS)

时间:2017-02-22 18:09:28

标签: python-3.x

def min(*args, **kwargs):
    key = kwargs.get("key", None)
    if len(args) == 1: 
        vars = args[0]
    else: 
        vars = args[:]
    ans = None
    for arg in vars:
        if ans is None:
            ans = arg
            continue
        if key is not None:
            if key(arg) < key(ans):
                ans = arg
        else:
            if arg < ans:
                ans = arg
        return ans

print(min("hello"))
print(min([[1,2], [3, 4], [9, 0]], key=lambda x: x[1]))

有人可以解释我上面代码的这一部分???

for arg in vars:
    if ans is None:
        ans = arg
        continue
    if key is not None:
        if key(arg) < key(ans):
            ans = arg
    else:
        if arg < ans:
            ans = arg

此外,有没有办法使用sorted()提前感谢。

1 个答案:

答案 0 :(得分:0)

以下是一些描述正在发生的事情的评论:

# vars represents the items we're attempting to find the minimum of.
# arg is the current item we're considering
for arg in vars:
    # ans is our running minimum value, and it initialized to None. If 
    # it's still None, this is the first arg we've tried, so just update 
    # the running minimum and move on to the next
    if ans is None:
        ans = arg
        continue
    # If a key function was passed, compare the result of passing our 
    # running minimum (ans) through it to the result of passing the 
    # current arg through it
    if key is not None:
        # If the result of the arg is less, make arg our new running 
        # minimum
        if key(arg) < key(ans):
            ans = arg
    # If there was no key function supplied, just compare the values of 
    # the running minimum (ans) and the current arg
    else:
        # If the current arg is smaller, make it the new running minimum
        if arg < ans:
            ans = arg

你能使用sorted吗?当然,如果提供了key,则传递,并返回排序列表中的第一项。但是,它不会非常有效。对整个列表进行排序比仅通过一次查找最小值要慢。