Table of Contents
回复内容:
Home Backend Development Python Tutorial python 用list of lists表示矩阵的问题?

python 用list of lists表示矩阵的问题?

Jun 06, 2016 pm 04:24 PM
for leetcode print range

题主刷leetCode的时候发现的一个小情况>_
python 初始化 a list of lists of integer,就用了如下方式(假设是4 x 4的方阵):
n = 4
matrix = [[0]*n]*n
print matrix
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
然后诡异的是,假如我只想给第二行的中间两个元素赋值:
matrix[1][1:3] = [1, 2]
结果会是:
print matrix
[[0, 1, 2, 0], [0, 1, 2, 0], [0, 1, 2, 0], [0, 1, 2, 0]]

但是如果用如下方式初始化matrix:
matrix = [[0 for col in range(n)] for row in range(n)]
matrix[1][1:3] = [1, 2]
print matrix
[[0, 0, 0, 0], [0, 1, 2, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
会是我想要的答案。

但是不知道第一种初始化方式错在哪里...

回复内容:

matrix = [[0]*n]*n
Copy after login
<span class="c">#!/usr/bin/python</span>
<span class="c">#encoding=utf-8</span>

<span class="c"># 内容来自python cookbook 第二版 第4.5章节</span>
<span class="c"># 在无须共享引用的条件下创建列表的列表</span>
<span class="c"># 避免隐式的引用共享</span>

<span class="n">multi</span> <span class="o">=</span> <span class="p">[</span> <span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">*</span> <span class="mi">5</span> <span class="p">]</span> <span class="o">*</span> <span class="mi">3</span> 
<span class="k">print</span> <span class="n">multi</span> 
<span class="n">multi</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s">'oops'</span>
<span class="k">print</span> <span class="n">multi</span>
<span class="c"># [ [ 'oops', 0, 0, 0, 0 ],[ 'oops', 0, 0, 0, 0],[ 'oops', 0, 0, 0, 0 ] ] </span>

<span class="c"># 等价方式</span>
<span class="n">row</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">*</span> <span class="mi">5</span> <span class="c"># row 列表中的5个子项都是引用0</span>
<span class="n">multi</span> <span class="o">=</span> <span class="n">row</span> <span class="o">*</span> <span class="mi">3</span> <span class="c"># multi 列表中的3个子项都是引用row</span>
<span class="c"># 解释: 在row创建中, 有无引用被复制完全不重要, 因为被引用的</span>
<span class="c"># 是数字, 而数字不可改变,换句话说,如果对象是不可改变的,则</span>
<span class="c"># 对象和对对象的引用实际没有区别。</span>
<span class="c"># multi创建中,包含了3个对[row] 内容引用,而其内容则是对一个</span>
<span class="c"># 列表的引用。因此修改时候其他3个引用也改变了,甚至row也改变</span>

<span class="c"># 解决方法:</span>
<span class="n">multilist_method1</span> <span class="o">=</span> <span class="p">[</span> <span class="p">[</span> <span class="mi">0</span> <span class="k">for</span> <span class="n">col</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span> <span class="p">]</span> <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="p">]</span>
<span class="n">multilist_method2</span> <span class="o">=</span> <span class="p">[</span> <span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">*</span> <span class="mi">5</span> <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="p">]</span>
<span class="n">multilist_method1</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s">'abc'</span>
<span class="n">multilist_method2</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s">'edf'</span>
<span class="k">print</span> <span class="n">multilist_method1</span>
<span class="k">print</span> <span class="n">multilist_method2</span>
Copy after login
赞同楼上,另外要处理矩阵相关的话用 NumPy 第一种是浅拷贝 这个问题,在《Python cookbook》第二版p148页提到,即隐式的引用共享问题。
解决的方案是使用列表推导。
详细你可以看看书。(不好意思手机码字懒得写太多了,希望能解决你的问题。) 刷leetcode用python坑多啊,昨天刚遇到一个python的除法和余数机制和c不一样啊
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

17 ways to solve the kernel_security_check_failure blue screen 17 ways to solve the kernel_security_check_failure blue screen Feb 12, 2024 pm 08:51 PM

Kernelsecuritycheckfailure (kernel check failure) is a relatively common type of stop code. However, no matter what the reason is, the blue screen error causes many users to be very distressed. Let this site carefully introduce 17 types to users. Solution. 17 solutions to kernel_security_check_failure blue screen Method 1: Remove all external devices When any external device you are using is incompatible with your version of Windows, the Kernelsecuritycheckfailure blue screen error may occur. To do this, you need to unplug all external devices before trying to restart your computer.

How to uninstall Skype for Business on Win10? How to completely uninstall Skype on your computer How to uninstall Skype for Business on Win10? How to completely uninstall Skype on your computer Feb 13, 2024 pm 12:30 PM

Can Win10 skype be uninstalled? This is a question that many users want to know, because many users find that this application is included in the default program on their computers, and they are worried that deleting it will affect the operation of the system. Let this website help users Let’s take a closer look at how to uninstall Skype for Business in Win10. How to uninstall Skype for Business in Win10 1. Click the Windows icon on the computer desktop, and then click the settings icon to enter. 2. Click "Apply". 3. Enter "Skype" in the search box and click to select the found result. 4. Click "Uninstall". 5

How to use for to find the factorial of n in JavaScript How to use for to find the factorial of n in JavaScript Dec 08, 2021 pm 06:04 PM

How to use for to find n factorial: 1. Use the "for (var i=1;i<=n;i++){}" statement to control the loop traversal range to "1~n"; 2. In the loop body, use "cj *=i" Multiply the numbers from 1 to n, and assign the product to the variable cj; 3. After the loop ends, the value of the variable cj is the factorial of n, and then output it.

PHP returns all the values ​​in the array to form an array PHP returns all the values ​​in the array to form an array Mar 21, 2024 am 09:06 AM

This article will explain in detail how PHP returns all the values ​​of an array to form an array. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. Using the array_values() function The array_values() function returns an array of all the values ​​in an array. It does not preserve the keys of the original array. $array=[&quot;foo&quot;=&gt;&quot;bar&quot;,&quot;baz&quot;=&gt;&quot;qux&quot;];$values=array_values($array);//$values ​​will be [&quot;bar&quot;,&quot;qux&quot;]Using a loop can Use a loop to manually get all the values ​​of the array and add them to a new

What is the difference between foreach and for loop What is the difference between foreach and for loop Jan 05, 2023 pm 04:26 PM

Difference: 1. for loops through each data element through the index, while forEach loops through the data elements of the array through the JS underlying program; 2. for can terminate the execution of the loop through the break keyword, but forEach cannot; 3. for can control the execution of the loop by controlling the value of the loop variable, but forEach cannot; 4. for can call loop variables outside the loop, but forEach cannot call loop variables outside the loop; 5. The execution efficiency of for is higher than forEach.

Explain in simple terms: Thoroughly understand the working principle of Go language range Explain in simple terms: Thoroughly understand the working principle of Go language range Mar 12, 2024 pm 02:18 PM

Go language is a concise and powerful programming language with unique design and features in many aspects. One of the most impressive features is the range keyword, which is used to iterate over data structures such as arrays, slices, maps, and channels. The flexibility and convenience of range make it easy to traverse complex data structures, but many people are confused about how it works. This article will explain how range works in a simple and in-depth way, and use specific code examples to help readers better understand. First, let's look at a simple example

How to use Range function in Java How to use Range function in Java Apr 19, 2023 pm 11:49 PM

Preface In Java, the Range method is available in both IntStream and LongStream classes. In IntStream class, it helps to return the sequential value of IntStream within function parameter scope. In the method, startInclusive(inclusive) and endExclusive(exclusive) are the two parameters used along with the increment step size, as mentioned before, the start value will be included and the end value will be excluded. In the case of LongStream, the only difference is the addition of the LongStream value. Range Syntax Let us see the syntax of range method in Java. IntStream range

How to avoid exceptions in simple for loops in JAVA? How to avoid exceptions in simple for loops in JAVA? Apr 26, 2023 pm 12:58 PM

Introduction In actual business project development, everyone should be familiar with the operation of removing elements that do not meet the conditions from a given list, right? Many students can immediately think of many ways to achieve it, but are all the ways you think of harmless to humans and animals? Many seemingly normal operations are actually traps, and many novices may fall into them if they are not careful. If unfortunately, an exception is thrown and an error is reported when the code is running, this is a blessing. At least the code can be discovered and solved in time without an error being reported, but various strange problems appear inexplicably in the business logic. This is more tragic. Because if you don't pay attention to this problem, it may cause hidden dangers for subsequent business. So, what are the implementation methods? What implementations might

See all articles