gpt4 book ai didi

python - 当需要元组类型参数时,我们是否可以始终使用列表类型作为函数参数?

转载 作者:太空宇宙 更新时间:2023-11-03 13:30:22 24 4
gpt4 key购买 nike

我一直在研究用 Python 编写的 Tensorflow API。我有两个问题。

<强>1。当需要元组时,我们能否始终使用列表类型作为函数参数?

如果我们查看有关 tf.placeholder 及其示例 ( https://www.tensorflow.org/api_docs/python/tf/placeholder ) 的官方 API 定义,我们会发现此函数的第二个参数是“形状”。在示例代码中,我们可以看到元组用于提供形状信息作为参数,如下所示。

x = tf.placeholder(tf.float32, shape=(1024, 1024))

但是,在官方教程页面(https://www.tensorflow.org/get_started/mnist/beginners)中,该示例使用列表 作为形状,而不是使用如下所示的元组。

y_ = tf.placeholder(tf.float32, [None, 10])

我知道列表和元组之间存在一些差异,例如不可变与可变。

如果列表支持元组的所有功能,那么我们是否总是可以安全地使用列表而不是元组作为函数参数?是否推荐?

<强>2。上面示例代码中的[None, 10]是什么意思?

在上面的示例代码中,使用了 [None, 10]。通常使用这样的表达方式吗?如果是这样,那么“无”是否也被认为是一种数字?

最佳答案

几乎所有你能在 tuple 上做的事你也能在 list 上做。然而,反之亦然,因为 tuple 是不可变的,而 list 是可变的。

但也有异常(exception)。由于元组是不可变的:

  • 它可以用作字典中的键。
  • 用于集合

列表旨在成为同类序列,而元组是异构数据结构。此外,tuple 在性能方面略胜一筹。

来自Python's Tuples and Sequences文档:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples).


所以你的问题的答案:

Can we always use a list type as a function parameter when a tuple is expected?

在大多数情况下,您可以使用 list 而不是 tuple,但并非总是如此。 但您不必为此担心太多,当您对 list 的使用可能出错时,Python 会提醒您。以下是您在这样做时会收到的错误:

TypeError: unhashable type: 'list'

例如:

>>> set([1, [1, 2]])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

>>> {[1, 2]: 1}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

关于python - 当需要元组类型参数时,我们是否可以始终使用列表类型作为函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48038883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com