6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python > [[0.0], [0.0], [0.0], [0.0], [0.0]]を簡略表記する > [[0.]]*5 > ***やってはいけない*** / Pythonインタープリタがプログラムを解釈しながら値や変数をメモリに展開していく様子を作図していただきました / 内包表記

Last updated at Posted at 2017-01-13
動作環境
GeForce GTX 1070 (8GB)
ASRock Z170M Pro4S [Intel Z170chipset]
Ubuntu 14.04 LTS desktop amd64
TensorFlow v0.11
cuDNN v5.1 for Linux
CUDA v8.0
Python 2.7.6
IPython 5.1.0 -- An enhanced Interactive Python.
gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
test_list1.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

alist = [[0.], [0.], [0.], [0.], [0.]]
print(alist)
blist = [[0.]]*5
print(blist)
結果
[[0.0], [0.0], [0.0], [0.0], [0.0]]
[[0.0], [0.0], [0.0], [0.0], [0.0]]

過去に記事へのコメントで教えていただいた。
その記事がどれだったか検索できない。。。

記憶に基づくと間違いをします、という例でした。

@shiracamus さんにコメントいただいたように**やってはいけない**書き方でした。

他の方法は要調査。

v0.2

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

# blist = [[0.]]*5  # *** mistake ***
blist = [[]]*5
print(blist)
for idx in range(0, 5):
    blist[idx] = [0.]
print(blist)
blist[0][0] = 123.456
print(blist)
結果
$ python test_list3.py 
[[], [], [], [], []]
[[0.0], [0.0], [0.0], [0.0], [0.0]]
[[123.456], [0.0], [0.0], [0.0], [0.0]]

まだ間違いがある可能性はあります。

検索用キーワード

(追記 2018/01/23)

  • List comprehension
6
6
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?