2014-10-28 111 views
0

我有一個列表,當用戶輸入一個字符串時生成:像這樣。它將採取每個單詞並將其附加到列表中。搜索最長的字符串列表

我有一個名爲max_l的變量,它查找列表中最長的字符串的長度。

我試圖做這樣的事情:

while max_l == len(mylist[x]): 
    print(mylist[x]) 
    a=a+1 

所以,它的意思是經過列表,每個項目與整數max_l比較。一旦找到該列表項目,就意味着打印它。它並沒有。我究竟做錯了什麼?

+2

什麼是'x'? '了'? – jonrsharpe 2014-10-28 21:29:49

+1

我不知道你在這裏做什麼,但最長的長度可以用'max(mylist,key = len)'來找到。 – 2014-10-28 21:34:39

回答

2

如果你要搜索的最長的字符串列表,你可以使用內置max()功能:

myList = ['string', 'cat', 'mouse', 'gradient'] 

print max(myList, key=len) 
'gradient' 

max需要一個「關鍵」參數,你可以指定功能(在這種情況下len,另一個內置函數),它應用於myList中的每個項目。

在這種情況下,對於myList中的每個字符串len(string)返回的最大結果(長度)是您最長的字符串,並且由max返回。

max文檔字符串:

max(iterable[, key=func]) -> value 
max(a, b, c, ...[, key=func]) -> value 

With a single iterable argument, return its largest item. 
With two or more arguments, return the largest argument. 

len文檔字符串:

len(object) -> integer 

Return the number of items of a sequence or mapping. 

生成列表從用戶輸入:

在回答您的通訊恩,我想我會補充一點。這是做這件事:

user = raw_input("Enter a string: ").split() # with python3.x you'd be using input instead of raw_input 

Enter a string: Hello there sir and madam # user enters this string 
print user 
['Hello', 'there', 'sir', 'and', 'madam'] 

現在使用max:

print max(user, key=len) 
'Hello' # since 'Hello' and 'madam' are both of length 5, max just returns the first one 
+0

我覺得有點愚蠢。我嘗試過,但它返回奇怪的值。 – lmsavk 2014-10-28 23:07:03

+0

如果你有一個像我上面使用的字符串列表,這應該可以正常工作。你如何準確地生成你的列表?另外,什麼樣的奇怪值?請參閱我的編輯 – Totem 2014-10-28 23:57:47

+0

如果它仍然無法正常工作,請讓我知道,並可能會將您的輸出內容發佈到此處的評論中(如果它不太長)或者在原始文章結尾處。 – Totem 2014-10-29 00:07:15