2016-07-05 68 views
2

我想要生成長度爲4的所有可能的DNA序列的列表,其中四個字符爲A,T,C,G。總共有4^4(256)種不同的組合。我包括重複,例如允許AAAA。 我已經看過itertools.combinations_with_replacement(iterable, r) 然而,根據輸入字符串的順序即長度爲4的字符串中的DNA字符的所有組合4

itertools.combinations_with_replacement('ATCG', 4) #diff results to... 
itertools.combinations_with_replacement('ATGC', 4) 

因爲這個列表輸出的變化,我在合併itertools.combinations_with_replacement(iterable, r)的嘗試,與itertools.permutations()

,使得通輸出itertools.permutations()itertools.combinations_with_replacement()。如下面所定義:

def allCombinations(s, strings): 
perms = list(itertools.permutations(s, 4)) 
allCombos = [] 
for perm in perms: 
    combo = list(itertools.combinations_with_replacement(perm, 4)) 
    allCombos.append(combo) 
for combos in allCombos: 
    for tup in combos: 
     strings.append("".join(str(x) for x in tup)) 

然而運行allCombinations('ATCG', li)其中li = []然後取 list(set(li))仍然只前進136個獨特序列,而不是256。

必須有一個簡單的方法來做到這一點,也許產生功率設置,然後過濾長度4?

+1

'itertools.product( 'ATCG',重複= 4)' ? – ayhan

+0

作爲答覆和生病接受 –

+0

這是非常相似。但我相信鏈接中的用戶要求在字符串 –

回答

6

您可以通過使用product實現這一目標。它使通過iterables的笛卡爾乘積:

a = 'ACTG' 

print(len(list(itertools.product(a, a, a, a)))) 
# or even better, print(len(list(itertools.product(a, repeat=4)))) as @ayhan commented 
>> 256 

但它返回的元組,因此,如果您正在尋找字符串:

for output in itertools.product(a, repeat=4): 
    print(''.join(output)) 

>> 'AAAA' 
    'AAAC' 
    . 
    . 
    'GGGG' 
+0

乾杯派爾。我很快就會接受 –

+1

'''[''.join(x)for itertools.product(a,repeat = 4)]''理解 –

0

你可能只是試試這個

l = [] 

s = 'ATCG' 

for a in s: 
    n1 = a 
    for b in s: 
     n2 = n1 + b 
     for c in s: 
      n3 = n2 + c 
      for d in s: 
       l.append(n3+d) 
+0

這*真*不能很好地擴展 - 對於正在尋找itertools方法的問題,這不是一個好的答案。 –

+0

你說得對,它沒有。但有時你必須使用目前最好的方法,而不是隻使用最好的可擴展選項。這個很容易理解。 –

+0

「這一個很容易理解」並不完全。爲了理解這些代碼需要在心裏牢記並跟蹤8個不同的變量。 – DeepSpace

相關問題