python - 在python中输入带有嵌套元组的元组列表
问题描述
我正在尝试输入以下提示:
from typing import *
x = [('a',), (('b',), ('c', 'd'))]
f( k : list[ tuple[str] | tuple[str, tuple[str]]]):
print(k)
并且不确定如何为此列表键入提示。
解决方案
鉴于您的示例,递归数据类型的正确注释将需要前向引用,如下所示:
Tstr = tuple[str, ...] | tuple['Tstr', 'Tstr']
这意味着 anTstr
要么是可变参数元组,要么是在每个坐标上str
包含 a 的嵌套元组。Tstr
示例居民将是
('b',) # B1: base case with 1 element -- tuple[str]
('c', 'd') # B2: base case with 2 elements -- tuple[str, str]
(('b',), ('c', 'd')) # inductive case of tuple[B1, B2]
(('c', 'd'), ('b',)) # inductive case of tuple[B2, B1]
((('b',), ('c', 'd')), ('b',)) # inductive case of tuple[tuple[B2, B1], B1]
...
等等
list[Tstr]
然后是一个非常好的类型提示(如果它的目的只是提示),但它不会通过 mypy 的类型检查(参见这个问题)。
如果您希望任何可用的python 类型检查器不抱怨,您需要满足于简化版本,即为归纳设置上限并明确指定允许的变体(例如Tstr = tuple[str, ...] | tuple[tuple[str, ...], tuple[str, ...]]
)。
推荐阅读
- validation - 如果单元格在谷歌表格中留空,则创建警告消息
- jquery - 更改 JQuery 以影响按钮的颜色,而不是背景?
- javascript - 通过ajax将项目从django模板中的forloop填充数据发送到django视图
- perl - 500 无法连接到 example.com:443(LWP::Protocol::https::Socket: SSL 连接尝试失败,出现未知错误 SSL 需要先读取)
- dart - 如何删除从 ListView 中按下的孩子
- sql - SQL Server:从一个表、另一个表或两者中获取唯一 ID
- ruby-on-rails - 为了将 Rails 应用程序推送到 Heroku,在 config/database.yml 中配置我的数据库的正确方法是什么?
- python - Python内部实现
- javascript - 流:计算属性。当类型为类时,在...中找不到可索引签名
- xslt - 如何在两个节点之间获取文本?