简体   繁体   English

如何检查python列表中的最后三个元素-它们是否是整数?

[英]How to check last three elements from a python list - whether they are integer?

I am using Python, version 2.7.2. 我正在使用Python 2.7.2版。

I have a task to check whether the last three elements from a list are integer? 我有一个任务来检查列表中的最后三个元素是否为整数? For example: 例如:

mylist = [String, Large_string_containing_integers_inside_it, 80, 40, 50]

For above list I want to check whether the last three elements are integer or not. 对于上面的列表,我想检查最后三个元素是否为整数。 How can I do this? 我怎样才能做到这一点?

Here is the code I am testing: 这是我正在测试的代码:

#!/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)

Use the built in isinstance and all functions, along with list slicing. 使用内置的isinstanceall功能以及列表切片。

if all(isinstance(i, int) for i in mylist[-3:]):
    # do something
else:
    # do something else
  • all checks if all elements in the given iterable evaluate to True . all检查给定iterable中的所有元素是否都为True
  • isinstance checks if the given object is an instance of the second parameter isinstance检查给定对象是否是第二个参数的实例
  • mylist[-3:] returns the last three elements of mylist mylist[-3:]返回mylist的最后三个元素

Also, if you're using Python 2 and have very large numbers in your list, check for the long (long integer) type as well. 另外,如果您使用的是Python 2,并且列表中有非常大的数字,则还要检查long (长整数)类型。

if all(isinstance(i, (int, long)) for i in mylist[-3:]):
    pass

This prevents numbers like 10**100 from breaking the condition. 这样可以防止数字10**100破坏条件。

If, however, your last three elements are strings, you have two options. 但是,如果最后三个元素是字符串,则有两个选择。

If you know none of the numbers are exceedingly large, you can use the isdigit string method. 如果您知道没有一个数字太大,则可以使用isdigit字符串方法。

if all(i.isdigit() for i in mylist[-3:]):
    pass

However, if they can be very large (around or over 2**31 ), use a try/except block and the built in map function. 但是,如果它们可能很大(大约2**31或以上),请使用try/except块和内置的map函数。

try:
    mylist[-3:] = map(int, mylist[-3:])
    # do stuff
except ValueError:
    pass
  • try defines the block of code to execute try定义要执行的代码块
  • except Exception catches the given exception and handles it without raising an error (unless told to do so) except Exception捕获给定的异常并在不引发错误的情况下进行处理(除非被告知这样做)
  • map applies a function to each element of an iterable and returns the result. map将函数应用于可迭代对象的每个元素,并返回结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM