简体   繁体   English

Python min和max内置模块混淆

[英]Python min and max built-in module confusion

I am supposed to write a function name shortest() that finds the length of the shortest string in a list of strings. 我应该编写一个函数名shortest(),它在字符串列表中查找最短字符串的长度。

The function shortest() takes one parameter: 1. a list of strings, textList 函数shortest()接受一个参数:1。字符串列表,textList

The function shortest() should return the length of the shortest string in text List. 函数shortest()应该返回文本List中最短字符串的长度。 You may assume that textList contains at least one element (string). 您可以假设textList包含至少一个元素(字符串)。

For example, the following would be correct output: 例如,以下是正确的输出:

>>> beatleLine = ['I', 'am', 'the', 'walrus']
>>> print(shortest(beatleLine))
1

-- -

When I finished writing the shortest() function, I came up with this solution 当我写完shortest()函数时,我想出了这个解决方案

def shortest(textList):
    return len(max(textList))

string = ['Hey', 'Hello', 'Hi']
print(shortest(string))

But I am confused as to why the max function returns the length of the shortest function instead of the min function. 但我很困惑为什么max函数返回最短函数的长度而不是min函数。

If I change max to min, the largest value is returned. 如果我将max更改为min,则返回最大值。 It almost seems as if min and max are switched. 几乎看起来好像最小和最大切换。

I am using Python 3.4 and running it on IDLE. 我正在使用Python 3.4并在IDLE上运行它。

max returns the largest item in an iterable. max返回可迭代中的最大项。 Since you didn't provide any key function to compare who is the largest it'll return the biggest element in lexicographical order: 由于您没有提供任何key功能来比较谁是largest它将返回字典顺序中最大的元素:

>>> max(['I', 'am', 'the', 'x', 'walrus'])
'x'

You need to tell max to which key function it will use to compare elements for deciding who is the largest : 您需要告诉max它将使用哪个键函数来比较元素以确定谁是最大的

>>> max(['I', 'am', 'the', 'walrus', 'x'], key=len)
'walrus'

That being said: 话虽如此:

>>> def shortest(textList):
...     return len(min(textList, key=len))

Alternatives using list comprehensions or map : 使用列表推导或map替代方案:

>>> min(len(text) for text in textList)

-- -

>>> min(map(len, textList))

If you compare the strings themselves as the function does (ie sort the list and display it), you'll see that they order them a specific way that gives the results you see. 如果你像函数那样比较字符串本身(即对列表进行排序并显示它),你会看到他们按照给出你看到的结果的特定方式对它们进行排序。

You want to use the key argument to pass a function that will give the length of the item instead of using the item itself. 您希望使用key参数传递一个函数,该函数将给出项的长度而不是使用项本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM