当前位置: 代码网 > it编程>前端脚本>Python > Python中的解包(tuple和dict的解包、*、**)的几种使用方法

Python中的解包(tuple和dict的解包、*、**)的几种使用方法

2025年11月24日 Python 我要评论
1. 问题为什么 np.random.randn(*images_example.shape) 中的 images_example.shape 前面需要加 *?2. 解决问题在 python 里面,*

1. 问题

为什么 np.random.randn(*images_example.shape) 中的 images_example.shape 前面需要加 *

2. 解决问题

在 python 里面,* 表示解包(一般是用于 list 和 tuple),** 也是解包,但它用于 字典 dict 的解包。因此,images_example.shape 前面的 * 其实也是解包的意思。

对于一个 tensor,它的属性 .shape返回的是一个 tuple(元组),但 np.random.randn() 的里面要的参数不能是一个 tuple 对象,而应该是 int。所以这里的 * 其实就是把 tuple 拆成了 int

3. 例子

example_list = [1, 2, 3]
print(f"{example_list = }")
print(f"{type(example_list) = }")
print("*example_list:", *example_list)
print()

example_tuple = (1, 2, 3)
print(f"{example_list = }")
print(f"{type(example_list) = }")
print("*example_tuple:", *example_list)

结果如下:

example_list = [1, 2, 3]
type(example_list) = <class 'list'>
*example_list: 1 2 3

example_list = [1, 2, 3]
type(example_list) = <class 'list'>
*example_tuple: 1 2 3

这个例子中,我们看到:

  • [1, 2, 3] 经过 * 后变为了 1 2 3 这样很诡异的样子
  • (1, 2, 3) 经过 * 后变为了 1 2 3 这样很诡异的样子

为什么说它"诡异"呢?

因为它的类型是不能求的,会报错:

tuple = (1, 2, 3)
print("type(*tuple):", type(*tuple))

结果如下:

traceback (most recent call last):
  file "c:\users\leovin\desktop\desktop\pytorch\books\src\leovin\encoder & decoder\exp_3.py", line 2, in <module>
    print("type(*tuple):", type(*tuple))
typeerror: type.__new__() argument 1 must be str, not int

那么 1 2 3 这种诡异的形式放到 np.random.randn() 中会怎么样?那么是分批放入,还是一起放入?我们做一个验证就可以知道了:

import numpy as np


a = (1, 2, 3)
np.random.seed(42)
a = np.random.randn(*a)

np.random.seed(42)
b = np.random.randn(1, 2, 3)

print(f"{a = }")
print(f"{b = }")

结果如下:

a = array([[[ 0.49671415, -0.1382643 ,  0.64768854],
        [ 1.52302986, -0.23415337, -0.23413696]]])
b = array([[[ 0.49671415, -0.1382643 ,  0.64768854],
        [ 1.52302986, -0.23415337, -0.23413696]]])

那么,答案很清晰了。(1, 2, 3) 这个 tuple 被拆成了 1 2 3,是按照 1, 2, 3 这样的样子放进 np.random.randn() 当中的,即 np.random.randn(*(1, 2, 3)) <=> np.random.randn(1, 2, 3)

到此这篇关于python中的解包(tuple和dict的解包、*、**)的几种使用方法的文章就介绍到这了,更多相关python 解包内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com