2013-11-02 33 views
0

我有這兩種功能:有人能告訴我爲什麼我的程序在Python 2.7而不是3.3中工作?

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) 

因此,當我跑的主要功能,並且得到作爲輸入(例如):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中工作?提前致謝。

回答

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 
[] 
+0

但是不執行'eval(input())'將它從一個字符串改爲整數? – kindrex735

+0

@ user2934394'eval'期望一個字符串不是列表,python2的'input()'已經將你的字符串轉換爲'list'。 –

+0

@ user2934394只需使用py3.x中的'input'和py2.x中的'raw_input'。還有一個py2to3工具可以爲你轉換程序。 –

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? ")) 
相關問題