[' 10.1.1.1','错误的IP地址']
def findIP(IP):
with open(tsvfile,'rt' )as f:
reader = csv.reader(f, delimiter='\t')
for row in reader:
if IP.strip() in row[0]:
x = row[1]
else:
x = "Activity Unknown"
return x
如果我删除了else语句,代码就有效,但只返回" Activity Unknown"当else语句存在时。我尝试了几种不同的方法来完成这项工作。他们都产生了相同的结果。
return row[1] if IP.strip() in row[0] else "Activity Unknown"
答案 0 :(得分:0)
1.当reader = []时,你不会进入循环。
2.您的表格功能不正确:
def findIP(IP):
with open(tsvfile,'rt' )as f:
reader = csv.reader(f, delimiter='\t')
for row in reader:
if IP.strip() in row[0]:
x = row[1]
else:
x = "Activity Unknown"
return x
3.你可以写得更短:
def findIP(IP):
reader = csv.reader(f, delimiter='\t')
try:
return reader[0][1] if IP.strip() in reader[0][1] else "Activity Unknown"
except IndexError:
return "Activity Unknown"