有人能告诉我为什么我的程序在Python 2.7而不是3.3中工作吗?

时间:2013-11-02 20:22:49

标签: python python-3.x

我有这两个功能:

def MatchRNA(RNA, start1, end1, start2, end2):
    Subsequence1 = RNA[start1:end1+1]
    if start1 > end1:
        Subsequence1 = RNA[start1:end1-1:-1]
    Subsequence2 = RNA[start2:end2+1]
    if start2 > end2:
        Subsequence2 = RNA[start2:end2-1:-1]
    return Subsequence1, Subsequence2


def main():
    RNA_1_list = ['A','U','G','U','G','G','G','U','C','C','A','C','G','A','C','U','C','G','U','C','G','U','C','U','A','C','U','A','G','A']
    RNA_2_list = ['C','U','G','A','C','G','A','C','U','A','U','A','A','G','G','G','U','C','A','A','G','C']
    RNA_Values = {'A': 1, 'U': 2, 'C': 3, 'G': 4}
    RNA1 = []
    RNA2 = []
    for i in RNA_1_list:
        if i in RNA_Values:
            RNA1.append(RNA_Values[i])
    for i in RNA_2_list:
        if i in RNA_Values:
            RNA2.append(RNA_Values[i])
    RNA = list(input("Which strand of RNA (RNA1 or RNA2) are you sequencing? "))       
    Start1, End1, Start2, End2 = eval(input("What are the start and end values (Start1, End1, Start2, End2) for the subsequences of the strand? "))
    Sub1, Sub2 = MatchRNA(RNA, Start1, End1, Start2, End2)
    print(Sub1)
    print(Sub2)

因此,当我运行main函数并输入(例如):RNA1,然后是3,14,17,28时,它应该打印两个列表[2,4,4,4,2,3,3,1,3,4,1,3][4,2,3,4,2,3,2,1,3,2,1,4]。当我测试这段代码时,我无意中使用了Python 2.7,它运行正常(没有那个eval),但是当我在3.3中运行它(并将eval放回去)时,它会打印两个列表,['1']和[]。有谁知道为什么它在3.3中不起作用或我如何让它在3.3中工作?提前谢谢。

2 个答案:

答案 0 :(得分:3)

input()在Python3中返回一个字符串,而在Python2中则相当于eval(raw_input)

输入RNA1

<强> Python3:

>>> RNA1 = []
>>> list(input("Which strand of RNA (RNA1 or RNA2) are you sequencing? "))
Which strand of RNA (RNA1 or RNA2) are you sequencing? RNA1
['R', 'N', 'A', '1']

<强> Python2:

>>> list(eval(input("Which strand of RNA (RNA1 or RNA2) are you sequencing? ")))
Which strand of RNA (RNA1 or RNA2) are you sequencing? RNA1
[]

答案 1 :(得分:0)

关闭,但问题的主要来源是:

 RNA = list(input("Which strand of RNA (RNA1 or RNA2) are you sequencing? "))

list()电话无论如何都没用。

在Python2中,当您输入RNA1时,input()会评估该符号并返回绑定到RNA1的列表。

在Python3中,input()会返回字符串 "RNA1",其中毫无意义;-) list()变为

['R', 'N', 'A', '1']

更改代码以在两个版本下运行的一种方法:首先在顶部添加:

try:
    raw_input
except:  # Python 3
    raw_input = input

然后更改输入行:

RNA = eval(raw_input("Which strand of RNA (RNA1 or RNA2) are you sequencing? "))
Start1, End1, Start2, End2 = eval(raw_input("What are the start and end values (Start1, End1, Start2, End2) for the subsequences of the strand? "))