Length of longest word in a list

后端 未结 6 1239
面向向阳花
面向向阳花 2020-12-06 19:10

What is the more pythonic way of getting the length of the longest word:

len(max(words, key=len))

Or:

max(len(w) for w in words)

6条回答
  •  借酒劲吻你
    2020-12-06 19:29

    Just for info using ipython %timeit

    In [150]: words
    Out[150]: ['now', 'is', 'the', 'winter', 'of', 'our', 'partyhat']
    
    In [148]: %timeit max(len(w) for w in words)
    100000 loops, best of 3: 1.87 us per loop
    
    In [149]: %timeit len(max(words, key=len))
    1000000 loops, best of 3: 1.35 us per loop
    

    Just updated with more words to demonstrate @Omnifarious's point/comment.

    In [160]: words = map(string.rstrip, open('/usr/share/dict/words').readlines())
    
    In [161]: len(words)
    Out[161]: 235886
    
    In [162]: %timeit max(len(w) for w in words)
    10 loops, best of 3: 44 ms per loop
    
    In [163]: %timeit len(max(words, key=len))
    10 loops, best of 3: 25 ms per loop
    

提交回复
热议问题