2013-05-02 109 views
0

字符串我有类似下面的字符串列表:的Python - 返回最长的从列表

stringList = ["a" , "aa", "aaa", "aaaa", "aaab", "aaac"] 

我所试图做的是返回列表中的所有最长的串,我一直在使用的最大尝试功能,但它只返回一个值,而在这种情况下,有3串用的4

感谢任何帮助的长度!

+0

1.find最长的字符串的长度2.filter长度等于说 – iMom0 2013-05-02 17:10:57

+0

你是什么意思是什么呢?也许这个? >> http://stackoverflow.com/questions/873327/pythons-most-efficient-way-to-choose-longest-string-in-list << – grooveplex 2013-05-02 17:11:10

回答

6

使用list comprehensionmax

>>> lis= ["a" , "aa", "aaa", "aaaa", "aaab", "aaac"] 

>>> le = max(len(x) for x in lis) #find out the max length  

>>> [x for x in lis if len(x) == le] #now filter list based on that max length 
['aaaa', 'aaab', 'aaac'] 
2

事情是这样的,也许:

longest_len = 0 
longest_strings = [] 

for s in stringList: 
    if len(s) > longest_len: 
     longest_len = len(s) 
     longest_strings = [s] 
    elif len(s) == longest_len: 
     longest_strings.append(s) 
+1

这是明确的最快的算法,而不是最Python的,但.. – 2013-05-02 17:12:37

+1

这不是最快的。浪费'追加'太多了。 – 2013-05-02 17:14:01

+0

@BlaXpirit timeit和惊讶......双榜遍历为100元和10000元较慢的1.22倍慢1.18倍。 [size = [abs(int(random.gauss(20,10)))+ 1 for _ in range(length)]]生成的字符串; stringList = [''.join(random.sample(longstring,s))for s in sizes]' – viraptor 2013-05-02 17:35:30

0

单列表解析(即使列表被处理多次):

[s for s in stringList if len(s) == len(max(stringList, key=len))] 

由于Python v2.5,min()和max()有一个允许的可选参数键你要指定比较方法。

+1

这个列表被处理了两次以上:'if'被检查了'stringList'中的每一个',所以'len(max(stringList,key = len))'计算了'len(stringList)'次。它会显示二次表现,更多的是可惜。 – DSM 2013-05-02 18:08:09

+0

@DSM:你说得对。我仍然必须习惯Python的解释性质。 – 2013-05-02 18:23:24