首先 ,我们可以在列表中找到任何字符串的最大长度:
stringlist = ['hi', 'hello', 'hey','ohman', 'yoloo', 'hello']#maxlength = max([len(s) for s in stringlist])maxlength = max(len(s) for s in stringlist) # omitting the brackets causes max # to operate on an iterable, instead # of first constructing a full list # in memory, which is more efficient
一点解释。这称为列表理解,它使您可以将一个列表 理解 为另一列表。该代码的
[len(s) for s instringlist]意思是“通过获取来生成类似列表的对象,
stringlist而对于
s该列表中的每个对象,请给我
len(s)(该字符串的长度)。
现在我们有了清单
[2, 5, 3, 5, 5,5]。然后,我们在其
max()上调用内置函数,该函数将返回
5。
现在 您已达到最大长度,可以过滤原始列表:
longest_strings = [s for s in stringlist if len(s) == maxlength]
就像英语中的读法一样:“对于字符串列表
s中的每个字符串
s,如果
len(s)等于,请给我该字符串
maxlength。”
最后
,如果要使结果唯一,则可以使用
set()构造函数来生成唯一集:
unique_longest_strings = list(set(longest_strings))
(我们呼吁
list()在删除重复项后将其转回列表。)
归结为:
ml = max(len(s) for s in stringlist)result = list(set(s for s in stringlist if len(s) == ml))
注意 :请勿使用名为的变量
list,因为它会覆盖
list类型名称的含义。



