簡體   English   中英

python:幫助計算二進制序列中1的比例

[英]python: help in calculation a proportion of 1's in binary sequence

我正在用python編寫程序。 它會隨機生成長度為10的宿主二進制字符串和長度為7的寄生蟲二進制字符串。 我現在需要做的是找到每個寄生蟲基因組中1的比例以及整個寄生蟲種群中1的總比例

import random
host_genome_length = 10
parasite_genome_length = 5
host_initial_population=15
parasite_initial_population=10
assert   parasite_initial_population >=0
parasite_initial_chance_1= 0.2
host_initial_chance_1=0.5
hosts=[]
for i  in range(host_initial_population):
    genome= []
    for j in range (host_genome_length):
        if random.random()< host_initial_chance_1:
            genome.append(1)
        else:
            genome.append(0)
    hosts.append(genome)
print "hosts:"
print  hosts

parasites=[]
for i  in range(parasite_initial_population):
    genome= []
    for j in range (parasite_genome_length):
        if random.random()< parasite_initial_chance_1:
            genome.append(1)
        else:
            genome.append(0)
    parasites.append(genome)

for i in range(host_initial_population-parasite_initial_population):
    parasites.append(None)
print "parasites:"
print parasites

例如,如果輸出為[1、0、0、1、1],[0、0、0、0、0],[0、0、0、0、0],[1、0、1、0 ,0],[1,0,0,0,0],[0,0,0,0,0],[0,0,1,0,0],[0,0,0,0,0 ],[0、0、0、0、0],[0、0、0、1、0],無,無,無,無,無]

我需要每個序列中1的比例和整個列表中1的總比例嗎?

如果一次只能得到一個結果,則可以這樣進行:

res = [1,0,0,1,1]
proportion = float(res.count(1))/len(res)

如果結果全部以列表列表形式返回:

res = [[1, 0, 0, 1, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 0, 1, 0, 0], [1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 1, 0], None, None, None, None, None]


total = sum([ x.count(1) for x in res if x<> None ]) # ignore the None elements
length = sum([len(x) for x in res if x <> None])
proportion = float(total)/length
#pairs of (oneCount, oneProportion)
def prepare(listList):
    result = []
    for subList in listList:
        sLUnitCount = subList.__len__()
        slOneCount = sum(subList)
        result.append((slOneCount, float(slOneCount)/sLUnitCount))
    return result

#individual proportions
def indivProp(listList):
    indiv = prepare(listList)
    return map(lambda x:x[1])

#total proportions
def totalProp(listList):
    indiv = prepare(listList)
    slOnesCounts = map(lambda x:x[0],indiv)
    totalOnes = sum(slOnesCounts)
    slUnitCounts = map(lambda x:x[0]/x[1], indiv)
    totalUnits = sum(slUnitCounts)
    return totalOnes/totalUnits

暫無
暫無

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

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