如何确定Python中嵌套数据结构的类型?

2023-11-24

我目前正在将一些 Python 翻译成 F#,具体来说神经网络和深度学习.

为了确保数据结构正确转换,需要 Python 中嵌套类型的详细信息。这type()函数适用于简单类型,但不适用于嵌套类型。

例如在 Python 中:

> data = ([[1,2,3],[4,5,6],[7,8,9]],["a","b","c"])
> type(data)
<type 'tuple'>

只给出第一层的类型。关于元组中的数组一无所知。

我希望有像 F# 那样的东西

> let data = ([|[|1;2;3|];[|4;5;6|];[|7;8;9|]|],[|"a";"b";"c"|]);;

val data : int [] [] * string [] =
  ([|[|1; 2; 3|]; [|4; 5; 6|]; [|7; 8; 9|]|], [|"a"; "b"; "c"|])

返回与值无关的签名

整型[][]*字符串[]

*         is a tuple item separator  
int [] [] is a two dimensional jagged array of int  
string [] is a one dimensional array of string

这可以或者如何在 Python 中完成?

TLDR;

目前,我将 PyCharm 与调试器一起使用,并在变量窗口中单击单个变量的视图选项以查看详细信息。问题是输出包含混合的值和类型,而我只需要类型签名。当变量类似于 (float[50000][784], int[50000]) 时,这些值就会产生妨碍。是的,我现在正在调整变量的大小,但这是一种解决方法,而不是解决方案。

e.g.

Using PyCharm 社区

(array([[ 0.,  0.,  0., ...,  0.,  0.,  0.],
        [ 0.,  0.,  0., ...,  0.,  0.,  0.],
        [ 0.,  0.,  0., ...,  0.,  0.,  0.],
        ...,     
        [ 0.,  0.,  0., ...,  0.,  0.,  0.],
        [ 0.,  0.,  0., ...,  0.,  0.,  0.],
        [ 0.,  0.,  0., ...,  0.,  0.,  0.]], dtype=float32),
  array([7, 2, 1, ..., 4, 5, 6]))

Using Spyder

Using Spyder variable viewer

Using Visual Studio 社区 with Visual Studio 的 Python 工具

(array([[ 0.,  0.,  0., ...,  0.,  0.,  0.],    
        [ 0.,  0.,  0., ...,  0.,  0.,  0.],  
        [ 0.,  0.,  0., ...,  0.,  0.,  0.],  
        ...,   
        [ 0.,  0.,  0., ...,  0.,  0.,  0.],  
        [ 0.,  0.,  0., ...,  0.,  0.,  0.],  
        [ 0.,  0.,  0., ...,  0.,  0.,  0.]], dtype=float32),  
  array([5, 0, 4, ..., 8, 4, 8], dtype=int64)) 

EDIT:

由于这个问题已经被关注,显然有人正在寻找更多细节,这是我的修改版本,它也可以处理numpy ndarray。谢谢Vlad对于初始版本。

还因为使用了变体游程长度编码还有没有更多的用处?对于异构类型。

# Note: Typing for elements of iterable types such as Set, List, or Dict 
# use a variation of Run Length Encoding.

def type_spec_iterable(iterable, name):
    def iterable_info(iterable):
        # With an iterable for it to be comparable 
        # the identity must contain the name and length 
        # and for the elements the type, order and count.
        length = 0
        types_list = []
        pervious_identity_type = None
        pervious_identity_type_count = 0
        first_item_done = False
        for e in iterable:
            item_type = type_spec(e)
            if (item_type != pervious_identity_type):
                if not first_item_done:
                    first_item_done = True
                else:
                    types_list.append((pervious_identity_type, pervious_identity_type_count))
                pervious_identity_type = item_type
                pervious_identity_type_count = 1
            else:
                pervious_identity_type_count += 1
            length += 1
        types_list.append((pervious_identity_type, pervious_identity_type_count))
        return (length, types_list)
    (length, identity_list) = iterable_info(iterable)
    element_types = ""
    for (identity_item_type, identity_item_count) in identity_list:
        if element_types == "":
            pass
        else:
            element_types += ","
        element_types += identity_item_type
        if (identity_item_count != length) and (identity_item_count != 1):
            element_types += "[" + `identity_item_count` + "]"
    result = name + "[" + `length` + "]<" + element_types + ">"
    return result

def type_spec_dict(dict, name):
    def dict_info(dict):
        # With a dict for it to be comparable 
        # the identity must contain the name and length 
        # and for the key and value combinations the type, order and count.
        length = 0
        types_list = []
        pervious_identity_type = None
        pervious_identity_type_count = 0
        first_item_done = False
        for (k, v) in dict.iteritems():
            key_type = type_spec(k)
            value_type = type_spec(v)
            item_type = (key_type, value_type)
            if (item_type != pervious_identity_type):
                if not first_item_done:
                    first_item_done = True
                else:
                    types_list.append((pervious_identity_type, pervious_identity_type_count))
                pervious_identity_type = item_type
                pervious_identity_type_count = 1
            else:
                pervious_identity_type_count += 1
            length += 1
        types_list.append((pervious_identity_type, pervious_identity_type_count))
        return (length, types_list)
    (length, identity_list) = dict_info(dict)
    element_types = ""
    for ((identity_key_type,identity_value_type), identity_item_count) in identity_list:
        if element_types == "":
            pass
        else:
            element_types += ","
        identity_item_type = "(" + identity_key_type + "," + identity_value_type + ")"
        element_types += identity_item_type
        if (identity_item_count != length) and (identity_item_count != 1):
            element_types += "[" + `identity_item_count` + "]"
    result = name + "[" + `length` + "]<" + element_types + ">"
    return result

def type_spec_tuple(tuple, name):
    return name + "<" + ", ".join(type_spec(e) for e in tuple) + ">"

def type_spec(obj):
    object_type = type(obj)
    name = object_type.__name__
    if (object_type is int) or (object_type is long) or (object_type is str) or (object_type is bool) or (object_type is float):            
        result = name
    elif object_type is type(None):
        result = "(none)"
    elif (object_type is list) or (object_type is set):
        result = type_spec_iterable(obj, name)
    elif (object_type is dict):
        result = type_spec_dict(obj, name)
    elif (object_type is tuple):
        result = type_spec_tuple(obj, name)
    else:
        if name == 'ndarray':
            ndarray = obj
            ndarray_shape = "[" + `ndarray.shape`.replace("L","").replace(" ","").replace("(","").replace(")","") + "]"
            ndarray_data_type = `ndarray.dtype`.split("'")[1]
            result = name + ndarray_shape + "<" + ndarray_data_type + ">"
        else:
            result = "Unknown type: " , name
    return result

我不认为它已经完成,但到目前为止它已经满足了我需要的一切。


正如我所评论的,这在 Python 中是不可能的,因为列表是无类型的。

你仍然可以假装这样做:

def typ(something, depth=0):
    if depth > 63:
        return "..."
    if type(something) == tuple:
        return "<class 'tuple': <" + ", ".join(typ(ding, depth+1) for ding in something) + ">>"
    elif type(something) == list:
        return "<class 'list': " + (typ(something[0], depth+1) if something else '(empty)') + ">"
    else:
        return str(type(something))

返回字符串<class 'tuple': <<class 'list': <class 'list': <class 'int'>>>,<class 'list': <class 'str'>>>>以你为例。

edit:为了让它看起来更像 F#,你可以这样做:

def typ(something, depth=0):
    if depth > 63:
        return "..."
    if type(something) == tuple:
        return " * ".join(typ(ding, depth+1) for ding in something)
    elif type(something) == list:
        return (typ(something[0]) if something else 'empty') + " []"
    else:
        return str(type(something, depth+1)).split("'")[1]

这将返回int [] [] * str []在你的例子中。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何确定Python中嵌套数据结构的类型? 的相关文章

随机推荐

  • 如何查看从给定文件开始的完整节点“require()”树?

    我需要查看某种依赖关系树 显示各种require 从特定文件开始 例如 如果我有一个server js像这样的文件 server js var myThing require myThing and a myThing js像这样的文件 m
  • 如何在 JavaScript 中从二进制数据创建 File 对象

    我可能在这里遗漏了一些简单的东西 但是如果给定从 AJAX 请求接收到的二进制数据 我如何在 JavaScript 中创建一个 File 对象呢 ajax url http example com image jpg success fun
  • 如何为图像创建三角形容器(x-浏览器)

    我将如何创建一个包含 IMG 的 DIV 其中 DIV 将图像切割成三角形 从而通过三角形仅显示图像的一部分 so div img src some image div 其中图像是正方形 但包含图像的 DIV 是三角形 http www s
  • 使用 Array.forEach 迭代 getElementsByClassName 的结果

    我想迭代一些 DOM 元素 我这样做 document getElementsByClassName myclass forEach function element index array do stuff 但我收到错误 document
  • 在 Safari 中禁用同源策略

    出于开发目的 我需要在我的计算机上的 Safari Windows 上 中禁用同源策略 在 Chrome 中 这可以通过使用标志启动来完成 disable web security Safari 中是否有等效的标志或隐藏设置 如果你想在Sa
  • 当我的 NodeJS 应用程序在我的计算机上运行时,本地网络上的其他人如何访问它?

    我有一个非常简单的问题 我用NodeJS做了一个网页游戏 我可以在并排打开多个浏览器窗口的情况下自己成功玩它 但是 我想知道其他本地计算机是否也可以访问并与我一起玩游戏 我天真地尝试使用这个网址 my ip address 8000这是行不
  • 在 Ruby 1.8 中将字符串简单转换为 UTF-8

    我知道在 Ruby 1 9 中你可以轻松地重新编码这样的字符串 s s encode UTF 8 Ruby 1 8 中的等效项是什么 它需要什么线路 我见过的所有教程都不必要地复杂 我不明白发生了什么 詹姆斯 爱德华 格雷二世有一个详细帖子
  • CRC16 ISO 13239 实施

    我正在尝试在 C 中实现 Crc16 我已经尝试了许多不同的实现 但大多数都给了我不同的值 这是我已经使用过的一些代码 private static int POLYNOMIAL 0x8408 private static int PRES
  • 无法选择 MKViewAnnotation 两次?

    我在地图上放置了图钉 当我点击它们时 我会调用didSelect 该函数仅在第一次点击该引脚时被调用 之后不会再次在同一引脚上调用该函数 除非我选择另一个引脚然后返回并点击它 对我来说 这听起来像是正在选择引脚 并且didSelect只能在
  • 我应该在哪里放置 Junit @Category 的接口类?

    我想定义项目范围的接口 用于 Category注释 并配置 Maven 在构建整个项目时排除其注释测试 In the 应用项目中有一个测试我想分类 Category Integration class Test public void te
  • Django 无法切换语言环境

    我有文件 locale es LC MESSAGES django mo 和 po 运行 makemessages 和compilemessages 绝对所有消息都已翻译 在settings py中有 USE I18N True LANGU
  • Laravel 中的位置标头

    我正在为我的大学的身份验证系统 Ucam Webauth 使用图书馆 这意味着我必须使用其中一种方法重定向到身份验证服务器 不幸的是 我无法退货Redirect to 因为这个图书馆的架构 图书馆本身使用header Location 但这
  • “kafka.zookeeper.ZooKeeperClientTimeoutException:等待连接超时”仅在列出主题期间

    我发现了一些主题相似但上下文不同的问题 我可以连接以创建主题 但无法列出主题 因为我收到了下面提到的错误 据我所知 人们在我时面临基本连接问题 我只是为了列出主题列表 如果重要的话 这是我的docker compose yml versio
  • IntelliJ switch 语句使用字符串错误:use -source 7

    我正在尝试使用 IntelliJ 在 Mac OS X 上 编译我使用 Eclipse 编写的一些代码 我尝试运行以下代码 switch category case below 20 below20 break case 20 to 29
  • Linux 中的 ps 实用程序(procps),如何检查使用哪个 CPU

    这是关于procps包 实用程序ps对于Linux 它可以打印每个进程 线程 最后使用的CPU数量吗 更新 不是 CPU 时间 10 秒 而是 CPU 编号 CPU0 CPU5 CPU123 ps 1 手册页说您可以使用psr field
  • 使用 awk 从不同文件中减去列

    我有两个文件夹 A1 和 A2 这两个文件夹中的文件名称和文件数量相同 每个文件有 15 列 文件夹 A1 中每个文件的第 6 列需要从文件夹 A2 中每个文件的第 6 列作为基底 我想将每个文件的第 2 列和第 6 列 相减后 打印到具有
  • 获取哈希符号后的请求部分

    我的网站有 AJAX 支持的搜索 它使用深度链接 当用户点击链接时 http example com articles tags Mac 20OS review 标签 Mac OS 和 评论 应该已经在搜索表单中选择 并且与 Mac OS
  • iOS 7 ANCS:发现主要 ANCS 服务 UUID

    在 iOS7 下 主要的 ANCS 服务是否需要不断进行广告宣传 或者是否需要在模糊设置中启用 使用自定义 CBPeripheralManager 使用 Apple 指定的服务和特征 UUID 实现 以便潜在的通知消费者成功发现它并订阅 A
  • HTML + CSS:没有句点的有序列表?

    我认为这个问题的答案是否定的 但是有人知道一种 HTML CSS 方法来创建一个数字后面没有句点的有序列表吗 或者 指定分隔符 理想情况下 我不想为每个数字使用不同的类进行列表样式图像 但这就是我到目前为止所能想到的 这看起来非常不语义 I
  • 如何确定Python中嵌套数据结构的类型?

    我目前正在将一些 Python 翻译成 F 具体来说神经网络和深度学习 为了确保数据结构正确转换 需要 Python 中嵌套类型的详细信息 这type 函数适用于简单类型 但不适用于嵌套类型 例如在 Python 中 gt data 1 2