リストは変更可能なオブジェクトなので、ll=l=[]
がll
があることを意味している[...]
が含まれています 全く同じオブジェクトはl
です。これはis
演算子を使用して確認することができる。
>>> ll is l
True
これを実証することができる次のよう
>>> a=b=[]
>>> a
[]
>>> b
[]
>>> a.append(1)
>>> a
[1]
>>> b # For all practical purposes, a is identical to b
[1]
>>> a is b
True
したがって、ラインll.append(l)
再帰オブジェクトが作成します!
>>> # Run the posted code
>>> import pprint
>>> pprint.pprint(ll)
[[1, 2, 3, 4],
<Recursion on list with id=2032187430600>,
[5, 6, 7, 8],
<Recursion on list with id=2032187430600>,
[9, 10, 11, 12],
<Recursion on list with id=2032187430600>]
l.append
方法は既に l
オブジェクトに新たに生成されたリストを追加し、2Dを作成するためll
リストは、実際には必要ありません:この明確上記のコードの状態を実行した後pprint
モジュールを使用 リスト:
>>> q=[[1,2,3,4]]
>>> q.append([5,6,7,8])
>>> q
[[1, 2, 3, 4], [5, 6, 7, 8]]
次のようにコードを書き換えることができます。
a = [1,2,3,4,5,6,7,8,9,10,11,12]
l = list()
f,k = 0,4
# range(1,4) iterates m through the values [1, 2, 3]
# This includes the first but excludes the last
for m in range(1,4):
# f and k are already integers, so no need for typecasting
# This append statement will append the 1D slice as a single unit
l.append(a[f:k])
# a += 1 is the same as a = a + 1 but is more compact
f += 4
k += 4
print(l)
# Will be [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
あなたが実際には2つの別々の空のリストを作成する必要がある場合、このようにそれを行うには、より良いです:
>>> q=list()
>>> w=list()
>>> q is w
False