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
288 views
in Technique[技术] by (71.8m points)

How to find the shortest string in a list in Python

This seems like a pretty simple problem, but I'm looking for a short and sweet way of doing it that is still understandable (this isn't code golf).

Given a list of strings, what's the easiest way to find the shortest string?

The way that is most obvious to me is roughly:

l = [...some strings...]
lens = map(l, len)
minlen, minind = min(lens)
shortest = l[minind]

but that seems like a lot of code for this problem (at least in python).

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The min function has an optional parameter key that lets you specify a function to determine the "sorting value" of each item. We just need to set this to the len function to get the shortest value:

strings = ["some", "example", "words", "that", "i", "am", "fond", "of"]

print min(strings, key=len) # prints "i"

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

2.1m questions

2.1m answers

60 comments

57.0k users

...