我有一個列表,當用戶輸入一個字符串時生成:像這樣。它將採取每個單詞並將其附加到列表中。搜索最長的字符串列表
我有一個名爲max_l的變量,它查找列表中最長的字符串的長度。
我試圖做這樣的事情:
while max_l == len(mylist[x]):
print(mylist[x])
a=a+1
所以,它的意思是經過列表,每個項目與整數max_l比較。一旦找到該列表項目,就意味着打印它。它並沒有。我究竟做錯了什麼?
我有一個列表,當用戶輸入一個字符串時生成:像這樣。它將採取每個單詞並將其附加到列表中。搜索最長的字符串列表
我有一個名爲max_l的變量,它查找列表中最長的字符串的長度。
我試圖做這樣的事情:
while max_l == len(mylist[x]):
print(mylist[x])
a=a+1
所以,它的意思是經過列表,每個項目與整數max_l比較。一旦找到該列表項目,就意味着打印它。它並沒有。我究竟做錯了什麼?
如果你要搜索的最長的字符串列表,你可以使用內置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
什麼是'x'? '了'? – jonrsharpe 2014-10-28 21:29:49
我不知道你在這裏做什麼,但最長的長度可以用'max(mylist,key = len)'來找到。 – 2014-10-28 21:34:39