如何在Python中的列表中找到最短的字符串 [英] 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]
但这似乎是解决这个问题的很多代码(至少在 python 中).
but that seems like a lot of code for this problem (at least in python).
推荐答案
min
函数 有一个可选参数key
,它允许您指定一个函数来确定每个项目的排序值".我们只需要将其设置为 len
函数得到最短的值:
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"
这篇关于如何在Python中的列表中找到最短的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!