2017-06-29 95 views
0

我使用了一個名爲ANARCI進行編號抗體序列工具和程序的輸出是這樣的:訪問值的元組的元組列表中的[錯誤]

[((1, ' '), 'E'), ((2, ' '), 'V'), ..., ((113, ' '), 'A')] 

我想要將編號保存在.csv文件中,並且無法訪問上面簡短部分中顯示的空字符串。其中一些將在其中有一個字母,我需要檢查字符串是否爲空。這是我寫這樣做代碼:

with open(fileName + '.csv', 'wb') as myFile: 
    # sets wr to writer function in csv module 
    wr = csv.writer(myFile, quoting=csv.QUOTE_ALL) 
    # writes in headers 
    wr.writerow(headers) 
    # iterates through numbering 
    for row in numbering: 
     # gets to the innermost tuple 
     for tup in row: 
      # checks if the string contains a letter 
      if tup[1] != ' ': 
       # makes the number and letter a single string 
       numScheme = str(tup[0])+str(tup[1]) 
       # creates a list of values to write 
       varList = [baNumbering,numScheme,row[1]] 
       wr.writerow(varList) 
      else: 
       # if the string does not contain a letter, the list of values is created without the string 
       varList = [baNumbering,tup[0],row[1]] 
       wr.writerow(varList) 
     baNumbering = baNumbering + 1 

我這背後的想法是for row in numbering:讓我到含元組中的元組,並for tup in row:可以讓我檢查最裏面的元組的索引。我想要varList成爲一個包含數字,編號(可能附帶字母)的列表,然後是字母 - 如下所示:["1","1","E"]["30","29B","Q"]。然而,我得到的錯誤:

Traceback (most recent call last): 
    File "NumberingScript.py", line 101, in <module> 
    Control() 
    File "NumberingScript.py", line 94, in Control 
    Num() 
    File "NumberingScript.py", line 86, in Num 
    SaveNumbering(numbering,numberingScheme) 
    File "NumberingScript.py", line 72, in SaveNumbering 
    WriteFile(numbering,numberingScheme,fileName) 
    File "NumberingScript.py", line 51, in WriteFile 
    if tup[1] != ' ': 
IndexError: string index out of range 

有沒有更好的方式來訪問元組中的字符串?我能找到的所有資源只包含元組列表,並沒有提及我在這裏所做的工作。

回答

2

當tup獲取'E'值並且您試圖獲取不存在的索引時異常會引發異常。

for row in numbering: 
      for tup in row: 
       if tup[1] != ' ': # Raised exception --> 'E'[1] 

如果我理解正確的目標,請嘗試使用此:

DATA = [((1, ' '), 'E'), ((2, ' '), 'V'), ((113, ' '), 'A')] 

def get_tuples(data): 
    for item in data: 
     for element in item: 
      if isinstance(element, tuple): 
       yield element 
      else: 
       continue 

for tup in get_tuples(DATA): 
    print(tup) 

輸出

(1, ' ') 
(2, ' ') 
(113, ' ') 
+0

感謝您更明確指出我的問題。但是,將來使用答案部分發布實際答案,並使用評論部分發布有用的評論,這些評論不是答案。你知道一種只訪問元組的方法,而不是導致錯誤的字符串? – MTJ