使用Python内置的max() 函数和key 参数来查找一个集合中最长的字符串。调用max(my_set, key=len) 来返回集合中最长的字符串,使用内置的len() 函数来确定每个字符串的权重--最长的字符串具有最大长度。
问题的提出
给出一个Python的字符串集。找到具有最大字符数的字符串--该集合中最长的字符串。
下面是几个字符串集的例子和所需的输出。
# {'Alice', 'Bob', 'Pete'} – --> 'Alice'
# {'aaa', 'aaaa', 'aa'} – --> 'aaaa'
# {''} – --> ''
# {} – --> ''
方法1:max()函数,关键参数设置为len()
使用Python的内置 [max()](https://blog.finxter.com/python-max/)函数,带一个关键参数,找到一个集合中最长的字符串,像这样。max(s, key=len).这将返回集合中最长的字符串s 使用内置的[len()](https://blog.finxter.com/python-len/)函数来确定每个字符串的权重--最长的字符串将是最大值。
下面是get_max_str() 函数的代码定义,该函数将一组字符串作为输入,并返回列表中最长的字符串,如果该集合为空,则返回ValueError 。
def get_max_str(my_set):
return max(my_set, key=len)
这是我们在运行所需的例子时得到的输出。
print(get_max_str({'Alice', 'Bob', 'Pete'}))
# 'Alice'
print(get_max_str({'aaa', 'aaaa', 'aa'}))
# 'aaaa'
print(get_max_str({''}))
# ''
如果你传递一个空的集合,Python 将引发一个ValueError: max() arg is an empty sequence ,因为你不能把一个空的迭代器传入max() 函数。
print(get_max_str({}))
# ValueError: max() arg is an empty sequence
方法 2:处理空集
如果你想在集合为空的情况下返回一个替代值,你可以修改get_max_str() 函数以包括第二个可选参数。
def get_max_str(my_set, fallback=''):
return max(my_set, key=len) if my_set else fallback
print(get_max_str({}))
# ''
print(get_max_str({}, fallback='EMPTY!!!!!!'))
# EMPTY!!!!!!
方法3:使用For Loop的不那么Pythonic的方法
一个不那么Pythonic但对初学者来说更易读的版本是下面这个基于循环的解决方案。
def get_max_str(my_set, fallback=''):
if not my_set:
return fallback
max_str = '' # set is not empty
for x in my_set:
if len(x) > len(max_str):
max_str = x
return max_str
print(get_max_str({'Alice', 'Bob', 'Pete'}))
# 'Alice'
print(get_max_str({'aaa', 'aaaa', 'aa'}))
# 'aaaa'
print(get_max_str({''}))
# ''
print(get_max_str({}, fallback='EMPTY!!!!!!'))
# EMPTY!!!!!!
方法4:Python集合中字符串的最大长度
要找到 最大长度的字符串,使用max(my_set, key=len) 函数来获得具有最大长度的字符串,然后将这个最大的字符串传入len() 函数来获得最大字符串的字符数。
len(max(my_set, key=len))
这里有一个更详细的例子。
def get_max_length(my_set):
return len(max(my_set, key=len))
print(get_max_length({'Alice', 'Bob', 'Pete'}))
# 5
print(get_max_length({'aaa', 'aaaa', 'aa'}))
# 4
print(get_max_length({''}))
# 0
print(get_max_length({}))
# ValueError: max() arg is an empty sequence