How to find the longest word with python?

前端 未结 4 1358
萌比男神i
萌比男神i 2020-12-11 12:34

How can I use python to find the longest word from a set of words? I can find the first word like this:

\'a aa aaa aa\'[:\'a aa aaa aa\'.find(\' \',1,10)]

         


        
4条回答
  •  情歌与酒
    2020-12-11 13:17

    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 :-) .

提交回复
热议问题