[英]isinstance not working when list is used to check in Python
我正在尝试加载一个文本文件,该文件具有两列数据,由一个标签分隔。 第一列的值可以是整数或浮点数,而第二列的值始终是浮点数。 现在,我正在使用isinstance
查看第一列是整数还是浮点数。 但是,当使用值列表或列表的最后一个元素时, isinstance
似乎不起作用。 这是我的代码:
time_t = []
with open(logF, 'r') as f:
for line in f:
data_t = line.split()
time_t.append(data_t[0])
time_length_max = time_t[-1]
print time_length_max
if isinstance(time_length_max, (int, long)):
print "True"
else:
print "False"
我得到的输出是:
10000
False
假设我声明time_length_max = 10000
,而不是time_length_max = time_t[-1]
,我得到:
10000
True
您可以按照建议的方式尝试
def num(s):
try:
return int(s)
except ValueError:
return float(s)
time_t = []
with open(logF, 'r') as f:
for line in f:
data_t = line.split()
time_t.append(num(data_t[0]))
time_length_max = time_t[-1]
print time_length_max
if isinstance(time_length_max, (int, long)):
print "True"
else:
print "False"
注意该值应该是文件中的数字,如果它是一个空字符串,则将引发异常。
split
返回字符串。 您可能想在询问字符串是否为整数实例之前将其转换为整数。
>>> type('10000')
<type 'str'>
>>> type(10000)
<type 'int'>
>>> type(int('10000'))
<type 'int'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.