Fill the list with tuples

I just play with a simulation ( "The First Law of Mendel’s Inheritance" ).

Before I can allow the creatures to mate and analyze the result, a population must be generated, i.e. the list must be filled with different numbers of three different types of tuples, without unpacking them.

When trying to get acquainted with itertools (I will need combinations later in the conjugate part), I came up with the following Solution:

import itertools k = 2 m = 3 n = 4 hd = ('A', 'A') # homozygous dominant het = ('A', 'a') # heterozygous hr = ('a', 'a') # homozygous recessive fhd = itertools.repeat(hd, k) fhet = itertools.repeat(het, m) fhr = itertools.repeat(hr, n) population = [x for x in fhd] + [x for x in fhet] + [x for x in fhr] 

which will result in:

 [('A', 'A'), ('A', 'A'), ('A', 'a'), ('A', 'a'), ('A', 'a'), ('A', 'a'), ('A', 'a'), ('A', 'a'), ('A', 'a')] 

Is there a more reasonable, pythonic or memorable way to save the final list, for example. without first generating lists for the three types of faces?

+7
source share
3 answers

You can use itertools.chain to combine iterators:

 population = list(itertools.chain(fhd, fhet, fhr)) 

Although I would say there is no need to use itertools.repeat when you just can do [hd] * k . Indeed, I would approach this simulation as follows:

 pops = (20, 30, 44) alleles = (('A', 'A'), ('A', 'a'), ('a', 'a')) population = [a for n, a in zip(pops, alleles) for _ in range(n)] 

or maybe

 allele_freqs = ((20, ('A', 'A')), (30, ('A', 'a')), (44, ('a', 'a'))) population = [a for n, a in allele_freqs for _ in range(n)] 
+6
source

That should work, I suppose.

 pops = [2,3,4] alleles = [('A','A'), ('A', 'a'), ('a','a')] out = [pop*[allele] for pop, allele in zip(pops,alleles)] print [item for sublist in out for item in sublist] 

I put CodeBunk code so you can run it.

+1
source
 population = 2*[('A', 'A')] + 3*[('A', 'a')] + 4*[('a', 'a')] 

or

 hd = ('A', 'A') # homozygous dominant het = ('A', 'a') # heterozygous hr = ('a', 'a') # homozygous recessive population = 2*[hd] + 3*[het] + 4*[hr] 
0
source

All Articles