2013-10-23 32 views
0

我是第一次使用python和使用python函數功能的新手。我已經寫THR像代碼:如何將任何函數參數附加到Python中的輸出列表

def chunks(l, n): 
    for i in range(0, len(l), n): 
     chunk = l[i:i+n] 
     G = chunk.count('G') 
     C = chunk.count('C') 
     A = chunk.count('A') 
     T = chunk.count('T') 
     G_C = G+C 
     Total_G_C_A_T = G_C+A+T 
     G_C_contents = ((G_C)/float(Total_G_C_A_T))*100 
     GC_Window100.append(G_C_contents) 
    print (GC_Window100) 
chunks (list3, 100) 
chunks (list3, 150) 
chunks (list3, 200) 

我的問題是:如何我可以列表爲計算附加n的值?就像我正在使用GC_Window100一樣,我希望100應該來自函數參數,以便我可以跟蹤列表,來自哪個塊。我需要多次重複這個功能。 和輸出欲想:

GC_Window100 = [30,32,31,42]

GC_Window150 = [18,20,22,20]

GC_Window200 = [15,13,16, 10] 。 。 。

任何幫助?提前致謝。

+0

你想N的遞增的循環?或者你想在for循環中使用它嗎? – jramirez

回答

1

有幾種方法可以做到這一點,但這是一個足夠簡單的方法。

tracked_responses = [] 
tracked_responses.append(chunks(list3, 100)) 

然後在你的chunks功能,您將返回這樣

return (n, CS_Window100) 

現在你tracked_responses一個元組的元組與作爲第一要素的輸入n列表,以及CS_Window100值作爲第二。

此時,將函數變量重命名爲CS_Window而非CS_Window100可能有意義。

你tracked_responses會是這個樣子:

[(100, [1.2, 1.4, 45.4]), (200, [5.4, 3.4, 1.0]), ...] 

如果您需要通過n能夠訪問值,那麼你可以施放元組的該列表字典和訪問像這樣。

tracked_responses_dict = dict(tracked_responses) 
print tracked_responses_dict[100] 

既然你是新來的Python

這裏是你可以做收拾你的代碼。

  1. 使用collections.counter

Collections.counter是一個很好的方式組,然後分配計數的迭代獨特的項目(如表)。

gcat_counts = collections.counter(chunk) 
g_c = gcat_counts.get('G', 0) + gcat_counts.get('C', 0) 
a_t = gcat_counts.get('A', 0) + gcat_counts.get('T', 0) 

使用get方法將確保您獲得某些值,即使該密鑰不存在。

所以一個修訂後的腳本可能是這樣的

import collections 

def chunks(l, n): 
    gc_window = [] 
    for i in range(0, len(l), n): 
     chunk = l[i:i + n] 
     gcat_counts = collections.counter(chunk) 
     g_c = gcat_counts.get('G', 0) + gcat_counts.get('C', 0) 
     a_t = gcat_counts.get('A', 0) + gcat_counts.get('T', 0) 
     total_gcat = g_c + a_t 
     g_c_contents = (g_c/float(total_gcat)) * 100 
     gc_window.append(g_c_contents) 
    return (n, gc_window) 

tracked_responses = [] 
tracked_responses.append(chunks(list3, 100)) 
tracked_responses.append(chunks(list3, 150)) 
tracked_responses.append(chunks(list3, 200)) 

tracked_responses_dict = dict(tracked_responses) 
print tracked_responses_dict[100] 
相關問題