Python';选择列表中最长字符串的最有效方法是什么?
我有一个可变长度的列表,我试图找到一种方法来测试当前正在评估的列表项是否是列表中包含的最长字符串。我使用的是Python 2.6.1 例如:Python';选择列表中最长字符串的最有效方法是什么?,python,list,list-comprehension,Python,List,List Comprehension,我有一个可变长度的列表,我试图找到一种方法来测试当前正在评估的列表项是否是列表中包含的最长字符串。我使用的是Python 2.6.1 例如: mylist = ['abc','abcdef','abcd'] for each in mylist: if condition1: do_something() elif ___________________: #else if each is the longest string contained in myli
mylist = ['abc','abcdef','abcd']
for each in mylist:
if condition1:
do_something()
elif ___________________: #else if each is the longest string contained in mylist:
do_something_else()
当然,我忽略了一个简单而优雅的列表理解?从列表本身,您可以使用:
len(each)==max(len(x)表示myList中的x)
或仅each==max(myList,key=len)
要获取列表中最小或最大的项,请使用内置的min和max函数:
lo = min(L)
hi = max(L)
与sort一样,您可以传入一个“key”参数,用于在比较列表项之前映射它们:
lo = min(L, key=int)
hi = max(L, key=int)
如果正确映射字符串并将其用作比较,则可以使用max函数。当然,我建议只查找一次最大值,而不是针对列表中的每个元素。如果有超过1个最长字符串(想想“12”和“01”)该怎么办 尝试使用该选项以获得最长的元素
max_length,longest_element = max([(len(x),x) for x in ('a','b','aa')])
然后是常规foreach
for st in mylist:
if len(st)==max_length:...
def longesentry(lstName):
totalEntries=len(lstName)
currentEntry=0
最长长度=0
当currentEntryint(最长长度):
longestLength=此条目
longesentry=currentEntry
currentEntry+=1
返回最长长度
或者更容易:
max(some_list , key = len)
不适用于Python2.4。有关2.4下要实现的代码,请参见和。它只返回第一个最长字符串:例如,
print(max([“this”,“does”,“work”],key=len))
只返回“this”
,而不是返回所有最长字符串。同上@AndersonGreen。该方法能否以同样好地捕获满足调用(键)的列表中的两个+元素的方式进行重新部署?继我前面的问题之后,我已经链接了一个响应,如果所有其他项都相等的话,它可以解决第一项问题……要获得每个最大元素,在线性时间内,您必须执行m=max(map(len,xs));[x代表x,如果len(x)==m]
。我认为一句话做不好。你能简单解释一下吗?
def LongestEntry(lstName):
totalEntries = len(lstName)
currentEntry = 0
longestLength = 0
while currentEntry < totalEntries:
thisEntry = len(str(lstName[currentEntry]))
if int(thisEntry) > int(longestLength):
longestLength = thisEntry
longestEntry = currentEntry
currentEntry += 1
return longestLength
def longestWord(some_list):
count = 0 #You set the count to 0
for i in some_list: # Go through the whole list
if len(i) > count: #Checking for the longest word(string)
count = len(i)
word = i
return ("the longest string is " + word)
max(some_list , key = len)