Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

python - Length of longest word in a list

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)

Or.. something else? words is a list of strings. I am finding I need to do this often and after timing with a few different sample sizes the first way seems to be consistently faster, despite seeming less efficient at face value (the redundancy of len being called twice seems not to matter - does more happen in C code in this form?).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Although:

max(len(w) for w in words)

does kind of "read" easier - you've got the overhead of a generator.

While:

len(max(words, key=len))

can optimise away with the key using builtins and since len is normally a very efficient op for strings, is going to be faster...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...