2014-02-08 65 views
0

我正在嘗試編寫一個返回最長長度元素數組的函數。我不是在尋找最長的元素,而是最長的元素s使用數組字典獲取數組中最長元素的數組

我採取的方法是創建一個數組的字典,其中的關鍵是長度和值是由密鑰指示的長度元素的數組。

這是代碼,我拿出

#initialise the dictionary 
longest = {} 
#this keeps track of the greatest length 
longestNum = 0 
for seq in proteinSeq: 
    if len(seq) >= longestNum: 
     longestNum = len(seq) 
     #check to see if the dic key exists 
     #if not initialise it 
     try: 
      longest[longestNum].append(seq) 
     except NameError: 
      longest[longestNum] = [] 
      longest[longestNum].append(seq) 

return longest[longestNum] 

它給了我一個KeyError: 6在第一longest[longestNum].append(seq) ...

有人可以幫助我發現這裏的問題是什麼?

回答

2

如果你嘗試讀取一個不存在的鍵,你會得到一個KeyError,不是NameError,因爲您的錯誤信息說。所以你抓住了一個錯誤的例外。

你可以使用

except KeyError: 

,但我可能會使用

longest.setdefault(longestNum, []).append(seq) 

代替,或使longest一個collections.defaultdict(list),在這種情況下,簡直是

longest[longestNum].append(seq). 

爲見this article快速比較defaultdict和setdefault 。

+0

哇,太酷了......真的允許一些不錯的行爲。我習慣於PHP中的強力陣列...所以這是一個很好的發現。 (我再接受5分鐘的答案) –

1

NameError更改爲KeyError,因爲如果密鑰在您的字典中不存在,則會引發KeyError,正如您在回溯中所見。

但是,在這種情況下,我不確定你需要字典。什麼是這樣的:

longestwords=[] 
longestlength=0 

for word in all_words: 

    if len(word) > longestlength: 
     longestwords=[word,] 
     longestlength=len(word) 
    elif len(word) == longestlength: 
     longestwords.append(word) 
1

假設我已經正確理解你的問題,下面是一個更簡短和更具說明性的版本。它也有不構建整個詞典的優勢不僅隨後放棄所有與除了那些你感興趣的短序列中的鍵值對。

>>> from itertools import takewhile 
>>> # sort the protein sequences by length and then reverse the new 
>>> # list so that the longest sequences come first.  
>>> longest_first = sorted(proteinSeq, key=len, reverse=True) 
>>> longestNum = len(longest_first[0]) 
>>> # take only those sequences whose length is equal to longestNum 
>>> seqs = list(takewhile(lambda x: len(x)==longestNum, longest_first)) 
+0

......除了排序是O(n log(n)),而上面的算法是O(n)。 –

+0

@HughBothwell:謝謝,我修改了我的答案。 – superjump