python列表最大长度_python – 列表中最长的字符串

我正在创建一个从列表中返回最长字符串值的函数.当只有一个字符串最多的字符串时,我的代码才有效.我试图让它打印所有最长的字符串,如果有多个字符串,我不希望它们被重复.当我运行它时,它只返回’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

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值