访问值的元组的元组列表中的[错误]
问题描述:
我使用了一个名为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
有没有更好的方式来访问元组中的字符串?我能找到的所有资源只包含元组列表,并没有提及我在这里所做的工作。
答
当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, ' ')
感谢您更明确指出我的问题。但是,将来使用答案部分发布实际答案,并使用评论部分发布有用的评论,这些评论不是答案。你知道一种只访问元组的方法,而不是导致错误的字符串? – MTJ