我正在创建一个从列表中返回最长字符串值的函数.当只有一个字符串最多的字符串时,我的代码才有效.我试图让它打印所有最长的字符串,如果有多个字符串,我不希望它们被重复.当我运行它时,它只返回’hello’,而我希望它还返回’ohman’和’yoloo’.如果项目没有列表,我觉得问题就在行中,但是我已经尝试了所有内容但它不起作用.
list = ['hi', 'hello', 'hey','ohman', 'yoloo', 'hello']
def length(lists):
a = 0
answer = ''
for item in lists:
x = len(item)
if x > a:
a = x
answer = item
elif x == a:
if item not in list:
answer = answer + ' ' + item
return answer
print length(list)
解决方法:
首先,我们可以找到列表中任何字符串的最大长度:
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
一点解释.这称为list comprehension,它允许您将一个列表理解为另一个列表.代码[string(s)in stringlist]意味着“通过获取stringlist生成类似列表的对象,并且对于该列表中的每个s,给我代替len(s)(该字符串的长度).
所以现在我们有一个清单[2,5,3,5,5,5].然后我们调用内置的max()函数,返回5.
现在你有了最大长度,你可以过滤原始列表:
longest_strings = [s for s in stringlist if len(s) == maxlength]
这就像读英文一样:“对于stringlist中的每个字符串s,如果len(s)等于maxlength,请给我字符串s.”
最后,如果要使结果唯一,可以使用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的变量,因为它会覆盖列表类型名称的含义.
标签:python
如果觉得《python列表最大长度_python – 列表中最长的字符串》对你有帮助,请点赞、收藏,并留下你的观点哦!