簡體   English   中英

這段代碼如何從一串整數中提取最大值和最小值?

[英]How does this code extract the max and min from a string of integers?

這是我在 codewars.com 上找到的解決此 kata 的解決方案。

def high_and_low(numbers):
  return " ".join(x(numbers.split(), key=int) for x in (max, min))

我不明白這個解決方案是如何工作的,x 函數看起來像一個排序函數,那么 OP 怎么沒有使用排序? 另外,元組 (max,min) 上的 for 循環如何提取最大值和最小值? 我迷路了。 任何與此相關的示例/鏈接也值得贊賞。 提前感謝您的努力。

根據max的文檔(以及類似的 min), key=int用於對可迭代對象進行排序,在這種情況下,它是執行numbers.split()后獲得的字符串列表。 然后 max 和 min 將從列表中選擇最大和最小整數

for x in (max, min)本質上用函數maxmin替換 x

一個稍微簡單的方法可能是首先提取整數列表,然后對其應用 max 和 min

def high_and_low(numbers):

  nums = list(map(int, numbers.split()))
  return min(nums), max(nums)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM