2014-04-10 6 views
0

에서 파이썬 목록 항목 :분할 나는라는 목록이 사용자 정의 인덱스

FirstSequenceToSplit

을하고 DNA 서열이 하나 개의 항목을 포함하고 말 :

'ATTTTACGTA'

이 항목의 길이를 쉽게 반환 할 수 있으므로 사용자는 길이가 10 자임을 알고 있으므로 사용자가 원하는 인덱스의 문자 [0 : 6]을 추출하려고합니다. , 그런 다음 새 목록에 두 개의 항목을 생성합니다. 첫 번째 항목은 사용자 정의 색인의 문자 다음에 추출되지 않은 다른 문자를 대체하는 물음표 뒤에 있고 두 번째 항목은 역수를 갖습니다. [: 5 0] 다음 항목과 당신이 얻을하는 새로운 목록 :

그래서 사용자가 그들이 원하는 것을하면 내가 원하는 것을 설명하기

[ 'ATTTT ?????', '을? [ACGTA ']

이것은 내가 FASTA 형식 ('> Sequence1/nATTTTACGTA ','> Sequence2/nATTGCACGTA '등)의 DNA 서열 세트를 가지고있는 훨씬 더 큰 문제의 일부입니다. 사용자는 그 ID에 기초하여 시퀀스를 선택할 수 있고 미리 정의 된 입력에 기초하여 그 시퀀스가 ​​분할되고 Sequence2a 및 Sequence2b ('> Sequence1a/n ????? ACGTA', '> Sequence1b/nATTTT ????? ''> Sequence2/nATTGCACGTA '등). 현재 시퀀스의 이름을 인쇄하여 문제를 해결했으며 사용자가 ID없이 시퀀스를 추출하여 연결을 선택하도록 한 다음 위에 표시된 문제를 해결하면 새 항목으로 새 목록을 만듭니다.

저는 초급자입니다. (필자는 당연히 분명합니다!) 주어진 코드의 설명에 감사드립니다.

import sys 
import re 

#Creating format so more user friendly 

class color: 
    PURPLE = '\033[95m' 
    CYAN = '\033[96m' 
    DARKCYAN = '\033[36m' 
    BLUE = '\033[94m' 
    GREEN = '\033[92m' 
    YELLOW = '\033[93m' 
    RED = '\033[91m' 
    BOLD = '\033[94m' 
    UNDERLINE = '\033[4m' 
    END = '\033[0m' 


fileName = raw_input("Give the name of the Fasta file you wish to divide up ") 
# i.e TopTenFasta 

#Reading in the sequences splitting them by the > symbol 
in_file = open(fileName,"r") 
sequences = in_file.read().split('>')[1:] 
in_file.close() 


#Putting all these sequences into a list 
allSequences = [] 
for item in sequences: 
    allSequences.append(item) 

#Letting you know how many sequences there are in total 
NumberOfSequences = len(allSequences) 
print color.BOLD + "The Number of Sequences in this list is: " +color.END, NumberOfSequences 

#Returning the names of the IDs to allow you to decide which ones to split 
SequenceIds = [] 
for x in allSequences: 
    SequenceIds.append(x[0:10]) 

print color.BOLD + "With the following names: " + color.END, "\n", "\n".join(SequenceIds) 

#-----------------------Starting the Splice ------------------------------------ 
#----------------------------------------------------------------------------- 
#------------------------------------------------------------------------------ 



#Choosing the sequence you wish to splice 
FirstSequenceToSplitID = raw_input(color.BOLD + "Which sequence would you like to splice " + color.END) 

#Seeing whether that item is in the list 
for x in SequenceIds: 
    if FirstSequenceToSplitID == x: 
     print "valid input" 

FirstSequenceToSplit = [] 

#making a new list (FirstSequenceToSplit) and putting into it just the sequence (no ID) 
for listItem in allSequences: 
    if listItem[0:10]==FirstSequenceToSplitID: 
     FirstSequenceToSplit.append(listItem[11:]) 

#Printing the Length of the sequence to splice 
for element in FirstSequenceToSplit: 
    print color.BOLD + "The Length of this sequence is" + color.END, len(element) 
+1

코드가 있습니까? – najjarammar

+0

안녕하세요, 내 게시물의 주요 질문에 집중하고 싶었지만 지금까지 한 일을 보여주기 위해 편집했습니다. 최근 사과를 코딩하기 시작한 이래로 매우 오랜 바람을 피웠습니다. ! – PaulBarr

답변

1

내가 함축 및 우편을 사용하면 가능한 모든 도움을 너무 많이 사용하면

내 지금까지되는 코드를 제공 할 수 있습니다 감사합니다. 코드에 주석을 달았지만 무엇인가가 명확하지 않은지 물어보십시오.

my_str = 'ATTTTACGTA' 

# This loop will check that 
# - the casting to int is ok 
# - there are only two numbers inputted 
# - stop >= start 
# - start > 0 
# - stop < len(my_str) 
while True: 
    try: 
     start, stop = map(int, raw_input(
      'Please enter start and stop index separated by whitespace\n').split()) 
     if stop < start or start < 0 or stop > len(my_str): 
      raise ValueError 
     break 
    except ValueError: 
     print 'Bad input, try again' 


# Loop over all chars, check if the current index is inside range(start, stop). 
# If it is, add (char, '?') to the array, if not, add ('?', char) to the array. 
# 
# This would give you an array of something like this: 
# [('?', 'A'), ('?', 'T'), ('T', '?'), ('T', '?'), ('?', 'T'), ('?', 'A'), 
# ('?', 'C'), ('?', 'G'), ('?', 'T'), ('?', 'A')] 
# 
# By using zip(*array), we unpack each element, and saves the first indexes as 
# one list, and the second indexes as another, giving you a list like this: 
# 
# [('?', '?', 'T', 'T', '?', '?', '?', '?', '?', '?'), 
# ('A', 'T', '?', '?', 'T', 'A', 'C', 'G', 'T', 'A')] 

chars = zip(*((c, '?') if i in range(start, stop) else ('?', c) 
       for i, c in enumerate(my_str))) 

# ''.join is used to concencate all chars into two strings 
my_lst = [''.join(s) for s in chars] 
print my_lst 

샘플 출력 :

Please enter start and stop index separated by whitespace 
4 
Bad input, try again 
Please enter start and stop index separated by whitespace 
5 4 
Bad input, try again 
Please enter start and stop index separated by whitespace 
e 3 
Bad input, try again 
Please enter start and stop index separated by whitespace 
4 5 
['????T?????', 'ATTT?ACGTA'] 
+1

고맙습니다. 코드에이 코드를 구현하려고합니다. 한 번 해보 셨으면 물어볼 것입니다. 분명한 도움을 주셔서 감사합니다! 그것은 내가 문제를 해결할뿐만 아니라 배우는 데 도움이됩니다! – PaulBarr

+0

나는 그것을 작동 시키려고 노력하고 있지만, 지금은 입력에 관계없이 [ 'ATTTTACGTA', '?']로 목록을 얻고 있습니다. 나는 또한 코드를 변경해야했다 : stop len (my_str) : ValueError를 올리면리스트의 길이가 1 (1 item)이되므로, 문자열 대신 목록에서이를 수행하는 것이 중요 할까? ? – PaulBarr

+0

목록 항목을 문자열로 저장하여이 문제를 해결 했으므로 코드 자체가 목록 자체에서 작동하지 않았습니다. – PaulBarr

0

이 표현이 작동합니다 :

[ c[0:n] + '?' * (len(c)-n), '?' * n + c[n:] ] 
+0

@PaulBarr'c'가 당신의 문자열임을 명확히하기 위해,'n'은 당신이 나눌 인덱스입니다. – photoionized

+0

감사합니다. 어쨌든 [2 : 6]과 같이 두 개의 인덱스 사이에서 나눌 수 있습니까? – PaulBarr

+0

@PaulBarr 당신이 3 개의 문자열을 원한다고 가정하면 위와 같이 다음과 같이 수정하십시오 :'[c [0 : n] + '?' * (len (c) -n), '?' * n + c [n : m] + '?' * (len (c) -m), '?' * m + c [m :]]'. 꽤 간단한 수학입니다. '?'대신 – photoionized