簡體   English   中英

如何檢查python列表中的最后三個元素-它們是否是整數?

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

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

使用內置的isinstanceall功能以及列表切片。

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塊和內置的map函數。

try:
    mylist[-3:] = map(int, mylist[-3:])
    # do stuff
except ValueError:
    pass
  • try定義要執行的代碼塊
  • except Exception捕獲給定的異常並在不引發錯誤的情況下進行處理(除非被告知這樣做)
  • map將函數應用於可迭代對象的每個元素,並返回結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM