2010-03-06 84 views
1

我有以下代碼:的Python:隨機序列

import string 
import random 

d =[random.choice(string.uppercase) for x in xrange(3355)] 
s = "".join(d) 

print s 

目前,它打印出的從字母隨機序列。但是,我需要它打印只包含四個字母的字母序列,例如'A','C','U','G'。這將如何完成?

感謝

奎因

+0

你在製作隨機RNA序列嗎? – 2010-03-06 21:36:19

回答

2

更改你問random.choice挑一套由:

import random 

d =[random.choice('ACUG') for x in xrange(3355)] 
s = "".join(d) 

print s 

編輯:作爲SilentGhost指出,如果你的最終目標是隻是做一個字符串,跳過中間名單更高的內存效率:

s = "".join(random.choice('ACUG') for x in xrange(3355)) 
+1

你不需要列表理解 – SilentGhost 2010-03-06 19:49:58

1

只需更換string.uppercase用序列(列表或字符串,例如)包含您的選擇。

0

您的問題不清楚。你的意思是你想選擇一個只有4個字符串的字符串?如果是的話做的事:

d =[random.choice(string.uppercase) for x in xrange(4)] 

或者,如果你想從只有四個選項列表中選擇,然後執行:

d =[random.choice("ACUG") for x in xrange(3355)] 
0

認爲的OP是想預先選擇4從string.uppercase字符數限制的樣品,然後創建一個基於一個3355項字符串:

import string 
import random 

num_samples = 4 
char_sample = random.sample(string.uppercase, num_samples) 
d =[random.choice(char_sample) for x in xrange(3355)] 
s = "".join(d) 

print s 
print char_sample 

在這種情況下,random.sample(人口,sample_count)將採取冷杉的護理t要求相當好。

但是,我同意其他答案/評論,這個問題有點含糊。