国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

Python創(chuàng)建二維數(shù)組實(shí)例(關(guān)于list的一個(gè)小坑)

2020-01-04 16:28:30
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

0.目錄

1.遇到的問(wèn)題

2.創(chuàng)建二維數(shù)組的辦法

•3.1 直接創(chuàng)建法

•3.2 列表生成式法

•3.3 使用模塊numpy創(chuàng)建

1.遇到的問(wèn)題

今天寫Python代碼的時(shí)候遇到了一個(gè)大坑,差點(diǎn)就耽誤我交作業(yè)了。。。

問(wèn)題是這樣的,我需要?jiǎng)?chuàng)建一個(gè)二維數(shù)組,如下:

m = n = 3test = [[0] * m] * nprint("test =", test)

輸出結(jié)果如下:

test = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

是不是看起來(lái)沒(méi)有一點(diǎn)問(wèn)題?

一開(kāi)始我也是這么覺(jué)得的,以為是我其他地方用錯(cuò)了什么函數(shù),結(jié)果這么一試:

m = n = 3test = [[0] * m] * nprint("test =", test) test[0][0] = 233print("test =", test)

輸出結(jié)果如下:

test = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]test = [[233, 0, 0], [233, 0, 0], [233, 0, 0]]

是不是很驚訝?!

這個(gè)問(wèn)題真的是折磨我一個(gè)中午,去網(wǎng)上一搜,官方文檔中給出的說(shuō)明是這樣的:

Note also that the copies are shallow; nested structures are not copied. This often haunts new Python programmers; consider:

>>> lists = [[]] * 3>>> lists[[], [], []]>>> lists[0].append(3)>>> lists[[3], [3], [3]]

What has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are (pointers to) this single empty list. Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way:

>>>>>> lists = [[] for i in range(3)]>>> lists[0].append(3)>>> lists[1].append(5)>>> lists[2].append(7)>>> lists[[3], [5], [7]]

也就是說(shuō)matrix = [array] * 3操作中,只是創(chuàng)建3個(gè)指向array的引用,所以一旦array改變,matrix中3個(gè)list也會(huì)隨之改變。

2.創(chuàng)建二維數(shù)組的辦法

2.1 直接創(chuàng)建法

test = [0, 0, 0], [0, 0, 0], [0, 0, 0]]

簡(jiǎn)單粗暴,不過(guò)太麻煩,一般不用。

2.2 列表生成式法

test = [[0 for i in range(m)] for j in range(n)]

學(xué)會(huì)使用列表生成式,終生受益。不會(huì)的可以去列表生成式 - 廖雪峰的官方網(wǎng)站學(xué)習(xí)。

2.3 使用模塊numpy創(chuàng)建

import numpy as nptest = np.zeros((m, n), dtype=np.int)

關(guān)于模塊numpy.zeros的更多知識(shí),可以去 python中numpy.zeros(np.zeros)的使用方法 看看。

以上這篇Python創(chuàng)建二維數(shù)組實(shí)例(關(guān)于list的一個(gè)小坑)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持VEVB武林網(wǎng)。


注:相關(guān)教程知識(shí)閱讀請(qǐng)移步到python教程頻道。
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 边坝县| 甘孜县| 巨野县| 顺义区| 固始县| 普洱| 禄劝| 两当县| 佳木斯市| 微山县| 合水县| 文成县| 闽侯县| 通山县| 宜昌市| 汉中市| 开远市| 红安县| 琼结县| 沧源| 抚州市| 永德县| 朝阳区| 临邑县| 贵德县| 吉林省| 建德市| 上虞市| 永泰县| 宜阳县| 长沙市| 海门市| 凤凰县| 蕉岭县| 武城县| 澳门| 云安县| 汉源县| 长乐市| 丹江口市| 和龙市|