Answers:
print(max(["this", "does", "work"], key=len))
仅返回"this"
而不是返回所有最长的字符串。
m=max(map(len,xs)); [x for x in xs if len(x) == m]
。我认为这不可能一口气完成。
如果最长的字符串超过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 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)
要获取列表中最小或最大的项目,请使用内置的min和max函数:
lo = min(L) hi = max(L)
与sort一样,您可以传入“ key”参数,该参数用于在比较列表项之前映射它们:
lo = min(L, key=int) hi = max(L, key=int)
http://effbot.org/zone/python-list.htm
如果您正确地将其映射为字符串并将其用作比较,则看起来可以使用max函数。我建议当然只查找一次最大值,而不是列表中的每个元素。
len(each) == max(len(x) for x in myList)
要不就 each == max(myList, key=len)
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