繁体   English   中英

在 Python 元组中输入提示

[英]Type hint in Python tuples

我有下面的代码,我知道该函数需要 2 个整数,所以(n : int, m : int) ,它返回一个包含任意长度整数的元组,因此-> tuple[int,...]

我认为这对于空元组T : tuple[()]也是正确的,因为函数中某个点的元组只有一个值。

但是我收到这个错误

main.py:14: error: Incompatible types in assignment (expression has type "Tuple[int]", variable has type "Tuple[]")

我错过了什么?


def vectorise(n : int, m : int) -> tuple[int,...]:
  '''creates a tuple of element n repeated m times'''
  T : tuple[()] = () #empty tuple
  counter : int = 0
  while counter < m:
    T = T + (n,) #in Python (n,) is a tuple with one element n
    counter+=1
  #as a result, T can be of arbitrary length
  return T

L = vectorise(100, 5)

变量T的类型为“空元组”。 您正在尝试为其分配一些不是空元组的内容。 因此,您会收到类型错误。

您要么需要确保只将空元组分配给T ,要么确保T的类型允许非空元组。

暂无
暂无

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

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