【问题标题】:I am trying to find the maximum length word in a sentence我试图在一个句子中找到最大长度的单词
【发布时间】:2023-03-04 01:24:01
【问题描述】:

我正在尝试在一个句子中找到最大长度的单词,比如

a = "my name is john and i am working in STACKOVERFLOWLIMITED"

为了获取这句话中最大的单词,我正在尝试类似

c = a.split(',')

c = ['my', 'name', 'is', 'john', 'and', 'i', 'am', 'working', 'in', 'STACKOVERFLOWLIMITED']

当我尝试打印最大 (C) 时

output - 'working'

为什么输出不包含“STACKOVERFLOWLIMITED”作为该句子中最长的单词?

【问题讨论】:

  • c = a.split(',') --> c = a.split(' ') 应该有空格而不是,

标签: python string max


【解决方案1】:

这就是为什么working 这个词被认为是按字母顺序排列的最大词,而不是长度。 试试这个:

result = max(a.split(), key=len)
print(result)

【讨论】:

    【解决方案2】:

    另一种方式是……

    sorted([(x,len(x)) for x in c],key= lambda x: x[1])[-1][0]
    

    【讨论】:

      猜你喜欢
      • 2021-07-07
      • 2017-03-30
      • 2015-08-26
      • 2014-09-26
      • 2012-02-02
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2021-11-01
      相关资源
      最近更新 更多