簡體   English   中英

如何在python中的一個for循環的元組output中獲取相同position的總和?

[英]How to get the sum of the same position in a tuple output of a for loop in python?

我寫了一個定義來迭代 200 多個文件並計算 DNA 序列中轉換和顛換的數量。 現在我想把這個for循環的output的第一列和第二列一起總結。

這是我重復 200 次的 output,因為我有 200 個文件,我想得到第一列 (0+1+1+1+1+...) 和第二列 (1+0+) 的總和0+0+....)

(0, 1) (1, 0) (1, 0) (1, 0) (1, 0) (1, 0) (1, 0) (1, 0) (1, 0) (1, 0) (0, 1) (1, 0) (0, 1) (1, 0) (0, 1) (1, 0)

我嘗試將定義打印為列表,然后匯總列表,但這些列表未定義,因為它們只是一個 for 循環 output,所以我無法匯總它們。

print([dna_comparison(wild_type= f, mut_seq= h)])

結果:

[(0, 1)]
[(1, 0)]
[(1, 0)]
[(1, 0)]
[(1, 0)]
[(1, 0)]
[(1, 0)]
[(1, 0)]

一種使用 itertools accumulate的解決方案,我認為它非常干凈:

from itertools import accumulate

your_list =  [(0, 1), (1, 0), (1, 0), ....]

*_, sum_ = accumulate(your_list, lambda x,y: (x[0]+y[0],x[1]+y[1]))
print(sum_)

不太干凈,更多 python 魔法,只與代碼高爾夫真正相關,但不導入任何東西:

tuple(map(sum, zip(*your_lst)))

我認為在這種情況下可以使用列表理解。

如果將所有這些元組對放入一個列表中(可能通過使用 for 循環):

outputs = [(0, 1), (1, 0), (1, 0), ....]

你可以做類似的事情

sum_totals = ( sum([x[0] for x in outputs]), sum([x[1] for x in outputs]) )

和 sum_totals 看起來像(對第一列求和,對第二列求和)

正如其他答案所示,您有多種解決方案。

我認為處理這個問題的最方便的方法是通過numpy ,特別是如果您隨后還使用這些元組進行進一步處理。

例如,假設t是您的元組集合,那么您可以將其轉換為numpy.array並像矩陣一樣訪問它,即使用行和列索引:

t = [(0, 1), (1, 0), (1, 0), (1, 0), (1, 0), (1, 0), (1, 0), (1, 0)]
t_array = np.array(t)   
t_array[:, 1]

>>> array([1, 0, 0, 0, 0, 0, 0, 0])

此時您可以簡單地按列對元素求和:

t_array.sum(axis=0)
>>> array([7, 1])

可以通過以下代碼實現:

arr = [[(0, 1)],
[(1, 0)],
[(1, 0)],
[(1, 0)],
[(1, 0)],
[(1, 0)],
[(1, 0)],
[(1, 0)]]
firstcolumn = 0
secondcolumn = 0  
for i in arr:
    for v in i:
        print(v[0], ' ', v[1])
        firstcolumn = firstcolumn + v[0]
        secondcolumn = secondcolumn + v[1]
        
print(firstcolumn, secondcolumn)
#         7             1

我認為您獲取數據的方式還不夠清楚。 我的意思是,是元組,但我們如何讀取這些元組?

你說你正在從不同的文件中讀取元組,所以我想它們還沒有在列表中。

例如:

import random

data_number = 200  # Simulating n number of data in files
wild_type: int = 0
mut_seq: int = 0
for _ in range(data_number):
    data = (random.randint(0, 1), random.randint(0, 1))  # Simulating the tuple reading from a file
    wild_type += data[0]
    mut_seq += data[1]

print(f'wild_type {wild_type} times. mut_seq {mut_seq} times.')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM