<p>使用重复操作符<code>*</code>创建列表列表创建一个包含元素的列表,其中每个列表项引用相同的内存位置。你知道吗</p>
<blockquote>
<p><strong>Note:</strong> if you will modify any of these 5 items (in the below code example). It indirectly means to update the value of other items (with the same value) as well.</p>
<p>You can print the id of list elements in both the cases using <strong>id()</strong> function. It's clear in below code example with output.</p>
</blockquote>
<pre><code># First case
list1 = [[67]] * 5
print(list1);
print(id(list1[0]))
print(id(list1[1]))
print(id(list1[2]))
print(id(list1[3]))
print(id(list1[4]))
"""
[[67], [67], [67], [67], [67]]
140366629136392
140366629136392
140366629136392
140366629136392
140366629136392
"""
</code></pre>
<p>列表理解是一个伟大的方式来处理上述问题的最佳(Python)的方式。你知道吗</p>
<blockquote>
<p><strong>Note:</strong> Unlike above, we can easily create a list of lists where each list item references different memory locations.</p>
<p>We can use <strong>id()</strong> function print the ids of items and see if it's like in the previous code example.</p>
</blockquote>
<pre><code># Second case
list2 = [[68] for i in range(5)]
print(list2);
print(id(list2[0]))
print(id(list2[1]))
print(id(list2[2]))
print(id(list2[3]))
print(id(list2[4]))
"""
[[68], [68], [68], [68], [68]]
140390813841224
140390813841032
140390813841480
140390813842056
140390813842120
"""
</code></pre>
<blockquote>
<p><strong>References:</strong> <a href="https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly">List of lists changes reflected across sublists unexpectedly</a></p>
</blockquote>
<p>谢谢。你知道吗</p>