[英]Python's most efficient way to choose longest string in list?
I have a list of variable length and am trying to find a way to test if the list item currently being evaluated is the longest string contained in the list.我有一个可变长度的列表,我试图找到一种方法来测试当前正在评估的列表项是否是列表中包含的最长字符串。 And I am using Python 2.6.1
我正在使用 Python 2.6.1
For example:例如:
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()
Surely there's a simple list comprehension that's short and elegant that I'm overlooking?当然,我忽略了一个简短而优雅的简单列表推导式?
From thePython documentation itself, you can use max
:从Python 文档本身,您可以使用
max
:
>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)
123456
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)
or much easier:或者更容易:
max(some_list , key = len)
What should happen if there are more than 1 longest string (think '12', and '01')?如果最长的字符串超过 1 个(想想“12”和“01”)会发生什么?
Try that to get the longest element尝试获得最长的元素
max_length,longest_element = max([(len(x),x) for x in ('a','b','aa')])
And then regular foreach然后定期 foreach
for st in mylist:
if len(st)==max_length:...
len(each) == max(len(x) for x in myList)
或者只是each == max(myList, key=len)
To get the smallest or largest item in a list, use the built-in min and max functions:要获取列表中最小或最大的项目,请使用内置的 min 和 max 函数:
lo = min(L)
hi = max(L)
As with sort, you can pass in a "key" argument that is used to map the list items before they are compared:与排序一样,您可以传入一个“key”参数,用于在比较列表项之前映射它们:
lo = min(L, key=int)
hi = max(L, key=int)
http://effbot.org/zone/python-list.htm http://effbot.org/zone/python-list.htm
Looks like you could use the max function if you map it correctly for strings and use that as the comparison.看起来你可以使用 max 函数,如果你正确地将它映射到字符串并将其用作比较。 I would recommend just finding the max once though of course, not for each element in the list.
当然,我建议只找到一次最大值,而不是针对列表中的每个元素。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.