[Learn python from scratch] 20. Python list operation skills and examples

list comprehension

The so-called list comprehension refers to the lightweight loop to create a list

  1. basic way

insert image description here

  1. Use if in the loop
    insert image description here

  2. 2 for loops
    insert image description here

  3. 3 for loops
    insert image description here

practise

Please write a piece of Python code to group the elements in a list, such as [1,2,3,…100] becomes [[1,2,3],[4,5,6]…]

Reference answer:

a = [x for x in range(1,101)]
b = [a[x:x+3] for x in range(0,len(a),3)]

copy of list

Look at the following code and say what is printed.

a = 12
b = a
b = 13
print(b)
print(a)

The output is:

13
12
nums1 = [1, 5, 8, 9, 10, 12]
nums2 = nums1
nums2[0] = 100
print(nums2)
print(nums1)

The output is:

[100, 5, 8, 9, 10, 12]
[100, 5, 8, 9, 10, 12]

think:

Why does the data in nums1 change when the data in nums2 is modified?

Assignment operations in Python are all transfers of references (that is, memory addresses). For mutable types, modifying the value of the original data will change the value of the assigned object.

How can nums1 and nums2 become two mutually independent and unaffected lists?

Use the list's copy method, or the copy module to assign a list.

The copy method of the list

Using the copy method of the list, you can directly copy the original list into a new list. This copy method is shallow copy.

nums1 = [1, 5, 8, 9, 10, 12]
nums2 = nums1.copy()  # 调用列表的copy方法,可以复制出一个新的列表

nums2[0] = 100

# 修改新列表里的数据,不会影响到原有列表里的数据
print(nums2)
print(nums1)

Use of the copy module

In addition to using the copy method of the list, Python also provides the copy module to copy an object. The copy module provides two methods of shallow copy and deep copy. They are used in the same way, but the effect of execution is different.

shallow copy

Shallow copy is a top-level copy of an object. The popular understanding is: the reference is copied, but the content is not copied.

import copy

words1 = ['hello', 'good', ['yes', 'ok'], 'bad']

# 浅拷贝只会拷贝最外层的对象,里面的数据不会拷贝,而是直接指向
words2 = copy.copy(words1)

words2[0] = '你好'
words2[2][0] = 'no'

print(words1)  # ['hello', 'good', ['no', 'ok'], 'bad']
# wrods2 里的 yes 被修改成了 no
print(words2)  # ['你好', 'good', ['no', 'ok'], 'bad']

deep copy

A deep copy is a recursive copy of all levels of an object.

import copy

words1 = ['hello', 'good', ['yes', 'ok'], 'bad']

# 深拷贝会将对象里的所有数据都进行拷贝
words2 = copy.deepcopy(words1)

words2[0] = '你好'
words2[2][0] = 'no'

print(words1)  # ['hello', 'good', ['yes', 'ok'], 'bad']
print(words2)  # ['你好', 'good', ['no', 'ok'], 'bad']

slice

Lists, like strings, also support slicing, which is actually a shallow copy.

words1 = ['hello', 'good', ['yes', 'ok'], 'bad']
words2 = words1[:]
words2[0] = '你好'
words2[2][0] = 'no'
print(words1)  # ['hello', 'good', ['no', 'ok'], 'bad']
print(words2) # ['你好', 'good', ['no', 'ok'], 'bad']

Advanced case

[Python] Python realizes the word guessing game-challenge your intelligence and luck!

[python] Python tkinter library implements GUI program for weight unit converter

[python] Use Selenium to get (2023 Blog Star) entries

[python] Use Selenium and Chrome WebDriver to obtain article information in [Tencent Cloud Studio Practical Training Camp]

Use Tencent Cloud Cloud studio to realize scheduling Baidu AI to realize text recognition

[Fun with Python series [Xiaobai must see] Python multi-threaded crawler: download pictures of emoticon package websites

[Play with Python series] [Must-see for Xiaobai] Use Python to crawl historical data of Shuangseqiu and analyze it visually

[Play with python series] [Must-see for Xiaobai] Use Python crawler technology to obtain proxy IP and save it to a file

[Must-see for Xiaobai] Python image synthesis example using PIL library to realize the synthesis of multiple images by ranks and columns

[Xiaobai must see] Python crawler actual combat downloads pictures of goddesses in batches and saves them locally

[Xiaobai must see] Python word cloud generator detailed analysis and code implementation

[Xiaobai must see] Python crawls an example of NBA player data

[Must-see for Xiaobai] Sample code for crawling and saving Himalayan audio using Python

[Must-see for Xiaobai] Technical realization of using Python to download League of Legends skin pictures in batches

[Xiaobai must see] Python crawler data processing and visualization

[Must-see for Xiaobai] Python crawler program to easily obtain hero skin pictures of King of Glory

[Must-see for Xiaobai] Use Python to generate a personalized list Word document

[Must-see for Xiaobai] Python crawler combat: get pictures from Onmyoji website and save them automatically

Xiaobai must-see series of library management system - sample code for login and registration functions

100 Cases of Xiaobai's Actual Combat: A Complete and Simple Shuangseqiu Lottery Winning Judgment Program, Suitable for Xiaobai Getting Started

Geospatial data processing and visualization using geopandas and shapely (.shp)

Use selenium to crawl Maoyan movie list data

Detailed explanation of the principle and implementation of image enhancement algorithm Retinex

Getting Started Guide to Crawlers (8): Write weather data crawler programs for visual analysis

Introductory Guide to Crawlers (7): Using Selenium and BeautifulSoup to Crawl Douban Movie Top250 Example Explanation [Reptile Xiaobai must watch]

Getting Started Guide to Crawlers (6): Anti-crawlers and advanced skills: IP proxy, User-Agent disguise, Cookie bypass login verification and verification code identification tools

Introductory Guide to Crawlers (5): Distributed Crawlers and Concurrency Control [Implementation methods to improve crawling efficiency and request rationality control]

Getting started with crawlers (4): The best way to crawl dynamic web pages using Selenium and API

Getting Started Guide to Crawlers (3): Python network requests and common anti-crawler strategies

Getting started with crawlers (2): How to use regular expressions for data extraction and processing

Getting started with reptiles (1): Learn the basics and skills of reptiles

Application of Deep Learning Model in Image Recognition: CIFAR-10 Dataset Practice and Accuracy Analysis

Python object-oriented programming basics and sample code

MySQL database operation guide: learn how to use Python to add, delete, modify and query operations

Python file operation guide: encoding, reading, writing and exception handling

Use Python and Selenium to automate crawling#【Dragon Boat Festival Special Call for Papers】Explore the ultimate technology, and the future will be due to you"Zong" #Contributed articles

Python multi-thread and multi-process tutorial: comprehensive analysis, code cases and optimization skills

Selenium Automation Toolset - Complete Guide and Tutorials

Python web crawler basics advanced to actual combat tutorial

Python introductory tutorial: master the basic knowledge of for loop, while loop, string operation, file reading and writing and exception handling

Pandas data processing and analysis tutorial: from basics to actual combat

Detailed explanation of commonly used data types and related operations in Python

[Latest in 2023] Detailed Explanation of Six Major Schemes to Improve Index of Classification Model

Introductory Python programming basics and advanced skills, web development, data analysis, and machine learning and artificial intelligence

Use 4 regression methods to draw prediction result charts: vector regression, random forest regression, linear regression, K-nearest neighbor regression
** [Learn python from zero] 18. Detailed explanation of basic operations of Python lists (1) **

Guess you like

Origin blog.csdn.net/qq_33681891/article/details/132277384