最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時(shí)間:2025年11月24日 09:50:41   作者:Le0v1n  
本文主要介紹了Python中的解包的使用,包括uple和dict的解包、*、**,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

1. 問題

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

2. 解決問題

在 Python 里面,* 表示解包(一般是用于 List 和 Tuple),** 也是解包,但它用于 字典 Dict 的解包。因此,images_example.shape 前面的 * 其實(shí)也是解包的意思。

對(duì)于一個(gè) tensor,它的屬性 .shape返回的是一個(gè) Tuple(元組),但 np.random.randn() 的里面要的參數(shù)不能是一個(gè) Tuple 對(duì)象,而應(yīng)該是 int。所以這里的 * 其實(shí)就是把 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)

結(jié)果如下:

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

這個(gè)例子中,我們看到:

  • [1, 2, 3] 經(jīng)過 * 后變?yōu)榱?1 2 3 這樣很詭異的樣子
  • (1, 2, 3) 經(jīng)過 * 后變?yōu)榱?1 2 3 這樣很詭異的樣子

為什么說它"詭異"呢?

因?yàn)樗念愋褪遣荒芮蟮?,?huì)報(bào)錯(cuò):

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

結(jié)果如下:

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() 中會(huì)怎么樣?那么是分批放入,還是一起放入?我們做一個(gè)驗(yàn)證就可以知道了:

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 = }")

結(jié)果如下:

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) 這個(gè) Tuple 被拆成了 1 2 3,是按照 1, 2, 3 這樣的樣子放進(jìn) np.random.randn() 當(dāng)中的,即 np.random.randn(*(1, 2, 3)) <=> np.random.randn(1, 2, 3)。

到此這篇關(guān)于Python中的解包(tuple和dict的解包、*、**)的幾種使用方法的文章就介紹到這了,更多相關(guān)Python 解包內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

富民县| 永登县| 土默特右旗| 如东县| 潞西市| 花垣县| 花垣县| 宣武区| 河池市| 新绛县| 潞西市| 四子王旗| 江都市| 榆中县| 进贤县| 天镇县| 韶山市| 张家口市| 荔波县| 泸西县| 西贡区| 安阳县| 万盛区| 曲松县| 富锦市| 宣城市| 南平市| 鞍山市| 怀安县| 永春县| 临海市| 虹口区| 陵川县| 江安县| 遂川县| 丰台区| 西贡区| 衡南县| 垣曲县| 江永县| 九龙城区|