我使用的是 Python,版本 2.7.2。
我的任务是检查列表中的最后三个元素是否为整数? 例如:
mylist = [String, Large_string_containing_integers_inside_it, 80, 40, 50]
对于上面的列表,我想检查最后三个元素是否为整数。 我该怎么做?
这是我正在测试的代码:
#!/usr/bin/python
line = ['MKS_TEST', 'Build', 'stability:', '1', 'out', 'of', 'the', 'last', '2', 'builds', 'failed.', '80', '40', '50']
if all(isinstance(i, int) for i in line[-3:]):
job_name = line[0]
warn = line[-3]
crit = line[-2]
score = line[-1]
if score < crit:
print ("CRITICAL - Health Score is %d" % score)
elif (score >= crit) and (score <= warn):
print ("WARNING - Health Score is %d" % score)
else:
print ("OK - Health Score is %d" % score)
请您参考如下方法:
使用内置的 isinstance 和 all 函数,以及列表切片。
if all(isinstance(i, int) for i in mylist[-3:]):
# do something
else:
# do something else
all检查给定 iterable 中的所有元素是否都评估为True。isinstance检查给定对象是否是第二个参数的实例mylist[-3:]返回mylist 的最后三个元素
此外,如果您使用的是 Python 2 并且列表中的数字非常大,请同时检查 long(长整型)类型。
if all(isinstance(i, (int, long)) for i in mylist[-3:]):
pass
这可以防止像 10**100 这样的数字破坏条件。
但是,如果您的最后三个元素是字符串,您有两个选择。
如果您知道没有一个数字特别大,您可以使用 isdigit 字符串方法。
if all(i.isdigit() for i in mylist[-3:]):
pass
但是,如果它们可能非常大(大约或超过 2**31),请使用 try/except block 和内置的 map 函数。
try:
mylist[-3:] = map(int, mylist[-3:])
# do stuff
except ValueError:
pass
try定义要执行的代码块except Exception捕获给定的异常并处理它而不引发错误(除非被告知这样做)map将函数应用于可迭代对象的每个元素并返回结果。
