简体   繁体   English

Python类型检查二维列表

[英]Python type check 2d list

How do I type check for a 2d list?如何键入检查二维列表? I know type checking a 1d list in a functions parameter would be:我知道在函数参数中检查一维列表的类型是:

apples = list(["granny smith","fiji"])
foo(apples)
def foo(fruits:list):
    print("Typed check passed")

But how do it for a 2d list?但是如何处理二维列表呢?

board=list([list([1,2]),list([3,4])])
bar(board)
def bar(board:list:list): # My Guess Attempt
    print("Type check passed")

You can use the generic concrete collections :您可以使用通用的具体集合

# for python >= 3.9
def bar(list[list[int]]):
    ...

# for older versions:
from typing import List

def bar(List[List[int]]):
    ...

Assuming, the type of the list elements should be int - otherwise just use the corresponding type or skip the second set of brackets.假设列表元素的类型应该是int - 否则只需使用相应的类型或跳过第二组括号。

board=list([list([1,2]),list([3,4])])
bar(board)
def bar(board:list[list]):
    print("Type check passed")

You are using type hinting, not type checking您正在使用类型提示,而不是类型检查

You can use this code您可以使用此代码

from typing import List
def bar(board: List[List[int]]):
    # your code
    print("Type check passed")

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

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