简体   繁体   中英

Finding longest word error?

I'm trying to find the longest word in Python but I'm getting the wrong result. The code below was done in interactive mode. I should've received 'merchandise' (10 characters) as the longest word/string but I got 'welcome' (7 characters) instead.

 str = 'welcome to the merchandise store' #string of words
 longest = []                             #empty list
 longest = str.split()                    #put strings into list
 max(longest)                             #find the longest string
 'welcome'                                #Should've been 'merchandise?'

It's sorting the strings alphabetically not by length, what you need is:

max(longest, key=len)

Let me clarify a little bit further. In Python the default comparison for strings is alphabetical. This means "aa" will be less than "abc" for all intents and purposes (cmp in python2 and < in python2/3). If you call max on the list without a key then it will compare using the default comparison. If you put in a key function then it will compare the key instead of the value. Another options (python2 only) is the cmp argument to max, which takes a function like cmp . I don't suggest this method because it's going to end up being something like cmp=lambda x,y: len(x)-len(y) which seems much less readable then just key=len and isn't supported in python3.

If you have any more questions about using key, I'd suggest reading this specifically note (7) which covers cmp and key for list.sort which uses them in the same manner.

You can also so do this:

str = 'welcome to the merchandise store'
sorted(str.split(), key=len)[-1]

Split it, sort them by length, then take the longest (last one).

Change your str.split() to str.split(" ")

Then,

max = []
for x in str.split(" "):
    if len(x) > len(max[0]):
        max = []
        max.append(x)
    elif len(x) == len(max[0]):
        max.append(x)

This is one way to do it without the lambda or key=len just using a for loop and list comprehension :

str = 'welcome to the merchandise store' 
longest = []                             
longest = str.split()
lst = []
for i in longest:
    x = len(i)
    lst.append(x)
y = [a for a in longest if max(lst)== len(a)]
print y[0]

Output:

merchandise

This is in Python 2, in Python 3 print (y[0])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM