簡體   English   中英

檢查列表中的項目類型是否相同並執行任務

[英]Check type of items in list are all same and perform task

我希望能夠創建一個接受列表的函數,檢查列表中的每個項目是否為某種類型(一次為一個項目),如果是,則執行計算。 對於此特定功能,我想計算整數列表的乘積。

我的功能:

def multpoly(items):
    typeInt = []
    total = 1
    for i in list:
        if type(i) is int:
            total = total * i
        elif type(i) is str:
            typelist.append(i)
        elif type(i) is list:
            typelist.append(i)
    return total
    return listInt

items = [1,2,3,4,5]
stringitems = ["1","2","3"]
listitems = [[1,1],[2,2]]

print(multpoly(items))
print(multpoly(stringitems))
print(multpoly(listitems))

我還希望能夠創建函數來執行相同的操作,將列表更改為字符串列表並將其連接,並將列表更改為列表列表並將它們連接起來。

此當前功能無效。 我收到一個錯誤-“'type'對象不可迭代”。

如果有人可以提出修復建議或可以解釋發生的事情,那就太好了! :)

您正在嘗試迭代list ,但該參數名為items 另外, i將是一個int ,但實際上它本身並不是int 您想要isinstance(i, int)type(i) is int 最后,您不能將str添加到inttotal ); 如果目標是在任何項目不是int時失敗,則需要在類型檢查失敗時進行處理(否則,您將跳過該項目,但仍會報告列表都是整數)。 您可能希望代碼更像這樣:

# This uses the Py3 style print function, accessible in Py2 if you include
from __future__ import print_function
# at the top of the file. If you want Py2 print, that's left as an exercise

class NotUniformType(TypeError): pass

def multpoly(items):
    total = 1
    for i in items:
        if not isinstance(i, int):
            raise NotUniformType("{!r} is not of type int".format(i))
        total *= i
    return total

try:
    print(multpoly(items), "Items in list are integers"))
except NotUniformType as e:
    print("Items in list include non-integer types:", e)

暫無
暫無

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

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