我正在尝试在python中读取文件的第5列。如果第三列匹配“Plop”,我将第三列存储在list1中,否则如果第五列匹配“toto”,我将第三列存储在list2中。然后,我所做的就是检查两个列表中每个元素的长度。当我运行我的代码时,我收到此错误:
if word1 in columns[:4]
^
SyntaxError: invalid syntax
我的代码如下:
word1=['Popo']
word2=['toto']
aList1 = list()
aList = list()
for line in open("test.txt"):
columns = line.split(" ")
#columns.lookup([toto])
if word1 in (columns[:4]):
aList1.insert(columns[:2])
if word2 in (columns[:4]):
aList.insert(columns[:2])
#print '\n'.join(aList1)
for entry in aList1:
try:
l = len(entry)
print "Length of", entry, "is", l
except:
print "Element", entry, "has no defined length"
for entry in aList:
try:
l = len(entry)
print "Length of", entry, "is", l
except:
print "Element", entry, "has no defined length"
答案 0 :(得分:2)
你最后错过了:,应该是:
if word1 in columns[:4]: