简体   繁体   English

Python .split列表可以调用,但索引超出范围?

[英]Python .split list is callable but index is out of range?

I am writing a code to translate DNA and am looking for some help. 我正在编写用于翻译DNA的代码,正在寻求帮助。

A sample input would look like:ACGTGC 输入示例如下所示:ACGTGC

and I'm looking for the output to be:["T","G","C","A","C","G"] 我正在寻找输出为:[“ T”,“ G”,“ C”,“ A”,“ C”,“ G”]

I also would like for the while loop to loop only as many times as the amount of characters in the input.(replace the 9 with a variable) 我还希望while循环仅循环输入中字符数的次数。(用变量替换9)

I am very thankful for all help! 我非常感谢您的帮助!

n = 0
i = 0
list_1 = []
text = raw_input("TYPE WITH SPACES BETWEEN LETTERS:")
hi = len(text)
while i < 9 : 
    split_string = text.split(" ")
    if split_string[n] == "A" : 
        list_1.append("T")
    elif split_string[n] == "T" :
        list_1.append("A")
    elif split_string[n] == "C" :
        list_1.append("G")
    elif split_string[n] == "G" :
        list_1.append("C")
    i = i +1
    n = n + 1
print list_1

How about just using split() to break up the input in one go: 仅使用split()一次性分解输入的效果如何:

>>> dnaSeq = raw_input("Enter a space-separated DNA string:").split()
Enter a space-separated DNA string:A C G T G C
>>> dnaSeq
['A', 'C', 'G', 'T', 'G', 'C']

And then use a dictionary that maps bases to their base pair to get the complementary strand: 然后使用将碱基映射到碱基对的字典来获得互补链:

>>> dnaPair = dict(A="T", T="A", C="G", G="C")
>>> complement = [dnaPair[base] for base in dnaSeq]
>>> complement
['T', 'G', 'C', 'A', 'C', 'G']

This should do it. 这应该做。

translate_dict={'A':'T',
        'T':'A',
        'C':'G',
        'G':'C'}
text=raw_input("TYPE WITH SPACES BETWEEN LETTERS:")
print [translate_dict[item] for item in text.upper().split(' ')]

Result: 结果:

TYPE WITH SPACES BETWEEN LETTERS:A T G G C C G T C
['T', 'A', 'C', 'C', 'G', 'G', 'C', 'A', 'G']

A one-liner in python 3 Python 3中的单线

text.translate(str.maketrans('ATCG','TAGC')).split(' ')

or even 甚至

raw_input('Type with spaces between  letters:'
).translate(str.maketrans('ATCG','TAGC')).split(' ')

or in Python 2 或在Python 2中

from string import maketrans
text.translate(maketrans('ATCG','TAGC')).split(' ')

Listening to everybody, I think I worked it out. 听大家,我想我已经解决了。 I don't have enough reputation to up vote, but I would!!! 我没有足够的声誉来投票,但是我会!!! (I also coded for Uracil and its "transcribed", not "translated". Thanks! (我也为Uracil及其“转录”而不是“翻译”编码。谢谢!

conv={"A":"T","T":"A","C":"G","G":"C","U":"A"}

outputDNA=""
inputDNA= raw_input("Type the DNA sequence you want transcribed: ")

for letter in inputDNA:
    outputDNA += conv[letter]
print outputDNA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM