python 如何用python找到最长的单词?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1192881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find the longest word with python?
提问by Niklas
How can I use python to find the longest word from a set of words? I can find the first word like this:
如何使用python从一组单词中找到最长的单词?我可以找到这样的第一个词:
'a aa aaa aa'[:'a aa aaa aa'.find(' ',1,10)]
'a'
rfind is another subset
'a aa aaa aa'[:'a aa aaa aa'.rfind(' ',1,10)]
'a aa aaa'
回答by balpha
If I understand your question correctly:
如果我正确理解你的问题:
>>> s = "a aa aaa aa"
>>> max(s.split(), key=len)
'aaa'
split()
splits the string into words (seperated by whitespace); max()
finds the largest element using the builtin len()
function, i.e. the string length, as the key to find out what "largest" means.
split()
将字符串拆分为单词(由空格分隔);max()
使用内置len()
函数查找最大元素,即字符串长度,作为找出“最大”含义的关键。
回答by ThomasH
Here is one from the category "How difficult can you make it", also violating the requirement that there should be no own class involved:
这是“你能做到多困难”类别中的一个,也违反了不应该涉及自己的类的要求:
class C(object): pass
o = C()
o.i = 0
ss = 'a aa aaa aa'.split()
([setattr(o,'i',x) for x in range(len(ss)) if len(ss[x]) > len(ss[o.i])], ss[o.i])[1]
The interesting bit is that you use an object member to maintain state while the list is being computed in the comprehension, eventually discarding the list and only using the side-effect.
有趣的是,在推导式中计算列表时,您使用对象成员来维护状态,最终丢弃列表并仅使用副作用。
But please do use one of the max()solutions above :-) .
但是请务必使用上面的max()解决方案之一 :-) 。
回答by Rohit
Another way to find longest word in string:
在字符串中查找最长单词的另一种方法:
a="a aa aaa aa"
b=a.split()
c=sorting(b,key=len)
print(c[-1])
回答by Md Shafiqul Islam
def largest_word(sentence):
split_sentence = sentence.split(' ')
largest_word = ''
for i in range(len(split_sentence)):
if len(split_sentence[i]) > len(largest_word):
largest_word = split_sentence[i]
print(largest_word)
sentence = "Improve your coding skills with python"
largest_word(sentence)