如何检查Python列表的最后三个元素是否为整数?

1 投票
1 回答
918 浏览
提问于 2025-04-17 14:01

我正在使用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)

1 个回答

7

使用内置的 isinstanceall 函数,还有列表切片。

if all(isinstance(i, int) for i in mylist[-3:]):
    # do something
else:
    # do something else
  • all 用来检查给定的可迭代对象中的所有元素是否都为 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 结构和内置的 map 函数。

try:
    mylist[-3:] = map(int, mylist[-3:])
    # do stuff
except ValueError:
    pass
  • try 定义了要执行的代码块。
  • except Exception 捕获给定的异常,并处理它而不抛出错误(除非特别指明)。
  • map 会将一个函数应用到可迭代对象的每个元素上,并返回结果。

撰写回答