2017-02-22 15 views
0
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])) 

Может кто-нибудь объяснить мне эту часть вышеуказанного кода ???Python Объясните, если ключ (arg) <ключ (ans)

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() спасибо заранее.

ответ

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, если он был предоставлен, и просто верните первый элемент в отсортированном списке. Однако это было бы не очень эффективно. Сортировка всего списка происходит медленнее, чем просто пройти один проход, чтобы найти минимум.