search
HomeBackend DevelopmentPython TutorialHow to solve pitfalls in Python multidimensional lists

Summary of common ideas for arrays:

(The default nums below is an array.) 1. Traverse the array Traversal:

for num in nums:
	xxxx

Traversal with index

for idx,num in enumerate(nums):
	xxxx

2. Dynamic programming (dp) Dynamic programming generally uses an array to save state. See 53. Maximum subarray and . Using arrays to save state is a very common practice. For example 36. Valid Sudoku, 73. Set matrix to zero.

3.Double pointer See 88. Merge two ordered arrays, 350. Intersection of two arrays II can be used for one array with left and right pointers. It can also be two pointers traversing two arrays. while index1<m and index2></m>

Common functions for lists

In Python, list is generally used to implement variable arrays. The following is listcommonly used functions. (Common operations for variable sequence types, only .sort is unique to list. Refer to the sequence operation documentation)

iterable are true (or the iterable is empty) Returns

多维列表的一个坑

创建多维列表,一般用

w, h = 2, 3
A = [[None] * w for i in range(h)]

等价于

A = [None] * 3
for i in range(3):
    A[i] = [None] * 2

而不是

 A = [[None] * 2] * 3

原因在于用*对列表执行重复操作并不会创建副本,而只是创建现有对象的引用*3创建的是包含 3 个引用的列表,每个引用指向的是同一个长度为 2 的列表。 如果你给一项赋值,就会发现这个问题:

>>> A[0][0] = 5
>>> A
[[5, None], [5, None], [5, None]]

第1天

217. 存在重复元素

给定数组,判断是否存在重复元素。 做法:

  1. 直接遍历(穷举)

  2. 排序后,比较每个元素和下一个元素

  3. 哈希表

直接遍历会超时。 2的时间复杂度是O(nlogn) 也就是排序的时间复杂度 3的时间复杂度是O(n),但需要额外的O(n)辅助空间。 (穷举法基本都能想到,但很容易超时,后面只有在穷举法能通过时才列出来。)

3比较简单,这里写一下3的做法:

return len(nums) != len(set(nums))

53. 最大子数组和

给定数组,求其中一个连续数组和的最大值。

比较容易想到的是用一个数组记录目前位置最大的值(动态规划)。

dp[i] 表示以i位置结尾的连续数组和的最大值。 最后返回dp数组中最大值。

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        length = len(nums)
        dp = [0 for i in range(length)]
        for i in range(length):
            dp[i] = max(dp[i - 1], 0) + nums[i]
        return max(dp)

题解给出了一种省略dp数组的方法:

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        pre = 0
        res = nums[0]
        for x in nums:
            pre = max(pre+x ,x)
            res = max(res, pre)
        return res

第2天

1. 两数之和

找出数组中两个数之和等于target的两数下标。

暴力枚举可以

但时间较长,时间复杂度$O(N^2)$

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        n = len(nums)
        for i in range(n):
            for j in range(i + 1, n):
                if nums[i] + nums[j] == target:
                    return [i, j]
        
        return []

哈希表

官方题解的一个比较巧妙的方式:使用哈希表(字典) 用字典记录出现过的数字的位置。 时间复杂度$O(N)$,空间复杂度$O(N)$

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashtable = dict()
        for i, num in enumerate(nums):
            if target - num in hashtable:
                return [hashtable[target - num], i]
            hashtable[nums[i]] = i
        return []

88. 合并两个有序数组

两个有序数组,将第二个数组nums2合并到第一个数组nums1

双指针

1.可以用双指针遍历两个数组:

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        # 两个中存在空数组的时,直接返回
        if m == 0:
            nums1[:] = nums2[:]
            return
        if n == 0:
            return

        index1,index2 = 0,0
        t = []
        while index1<m><p>官方版本,更简洁、清楚。</p>
<pre class="brush:php;toolbar:false">class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        sorted = []
        p1, p2 = 0, 0
        while p1 <h4 id="暴力-追加后排序">(暴力) 追加后排序</h4><ol start="2" class=" list-paddingleft-2"><li><p>更简单粗暴的方式是直接将<code>nums2</code>追加到<code>nums1</code>后,进行排序。
及其简单而且效果很好。</p></li></ol><pre class="brush:php;toolbar:false">class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        nums1[m:] = nums2
        nums1.sort()

第3天

350. 两个数组的交集 II

以数组形式返回两数组的交集(数组形式,返回结果中每个元素出现的次数,应与元素在两个数组中都出现的次数一致)。 排序后双指针遍历。

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        nums1.sort()
        nums2.sort()
        i = 0
        j = 0
        result = []
        while i<len>nums2[j]):
                j+=1
            else:
                result.append(nums1[i])
                i+=1
                j+=1
       
        return  result</len>

121. 买卖股票的最佳时机

只需要记录下当前最低价,遍历价格过程中,用当前价格-最低价 就是当前可获得的最大利润。另外如果出现了更低的价格,则最低价也要更新。(一个朴素的想法,要是我在最低点买进就好了) 总的最大利润就是这些利润中的最大值。

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        r = 0
        min_price = float('inf')  # float('inf')表示正无穷
        for price in prices:
            min_price = min(min_price, price)  # 截止到当前的最低价(买入价)
            r = max(r, price - min_price)  # 截止到目前的最高利润
        return r

第4天

566. 重塑矩阵

给定一个mxn的数组,重构为rxc的数组。 比较简单的想法是把数组拉平为一位数组,然后逐个填充到新的数组中:

class Solution:
    def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
        m,n = len(mat), len(mat[0])
        if m*n != r*c:
            return mat
        arr = []
        for row in mat:
            for x in row:
                arr.append(x)
        arr_index = 0
        newmat = [[0 for j in range(c)]for i in range(r)]
        for i in range(r):
            for j in range(c):
                newmat[i][j] = arr[arr_index]
                arr_index += 1
        return newmat

官方提供了一种直接计算下标的方法:

class Solution:
    def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:
        m, n = len(nums), len(nums[0])
        if m * n != r * c:
            return nums
        
        ans = [[0] * c for _ in range(r)]
        for x in range(m * n):
            ans[x // c][x % c] = nums[x // n][x % n]
        
        return ans

118. 杨辉三角

找规律题。可以直接按照生成的规律生成数组。在「杨辉三角」中,每个数是它左上方和右上方的数的和。

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        res = [[]for _ in range(numRows)]
        res[0] = [1]
        for i in range(1,numRows):
            res[i].append(1)
            for j in range(0,len(res[i-1])-1):
                res[i].append(res[i-1][j] + res[i-1][j+1])
            res[i].append(1)

        return res

第5天

36. 有效的数独

判断当前数独是否有效(不需要填充数独) 只要用3个二维数组维护9行、9列、9个九宫格。

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        row = [[] * 9 for _ in range(9)]
        col = [[] * 9 for _ in range(9)]
        nine = [[] * 9 for _ in range(9)]
        for i in range(len(board)):
            for j in range(len(board[0])):
                tmp = board[i][j]
                if not tmp.isdigit():
                    continue
                if (tmp in row[i]) or (tmp in col[j]) or (tmp in nine[(j // 3) * 3 + (i // 3)]):
                    return False
                row[i].append(tmp)
                col[j].append(tmp)
                nine[(j // 3) * 3 + (i // 3)].append(tmp)
        return True

73. 矩阵置零

如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。 A: 利用数组的首行和首列来记录 0 值 另外用两个布尔值记录首行首列是否需要置0

class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        #标记
        m,n = len(matrix), len(matrix[0])
        row = any(x == 0 for x in matrix[0])
        col = any(matrix[r][0] == 0 for r in range(m) )
        
        for i in range(m):
            for j in range(n):
                if matrix[i][j] == 0:
                    matrix[i][0] = 0
                    matrix[0][j] = 0
                    
        #置零
        for i in range(1,m):
            for j in range(1,n):
                if matrix[i][0] == 0 or matrix[0][j] == 0:
                    matrix[i][j] = 0
        if row:
            for j in range(0,n):
                matrix[0][j] = 0
        if col:
            for i in range(0,m):
                matrix[i][0] = 0
function Function
nums.sort(key,reversed) (original)Follow The key is sorted in ascending order, reversed can specify whether to reverse.
sorted(nums,key,reversed) Usage is similar to nums.sort, but returns another array , the original array remains unchanged.
s.append(x) Append x to the end of the sequence
s.extend(t) or s = t extend s
x in with the content of t s Determine whether x is in the array nums.
len(s) Return s length
max(s), min(s) Return sMaximum value, minimum value
all( iterable) Returns True# if all elements of
##any(iterable) True if any element of iterable is true. If the iterable is empty, returns False.

The above is the detailed content of How to solve pitfalls in Python multidimensional lists. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

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 Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use