[Learn python from zero] 18. Detailed explanation of the basic operations of Python lists (1)

Introduction to the list

Think about it:

The strings learned earlier can be used to store a string of information, so think about it, how to store the names of all the students in our class?

Is it feasible to define 100 variables, and each variable stores a student's name? Is there a better way?

Answer: list

the list

1. The format of the list

Define the format of the column:[元素1, 元素2, 元素3, ..., 元素n]

The variable tmp is of type list

tmp = ['xiaoWang',180, 65.0]

Elements in a list can be of different types

2. Use subscripts to get list elements

namesList = ['xiaoWang','xiaoZhang','xiaoHua']
print(namesList[0])
print(namesList[1])
print(namesList[2])

result:

xiaoWang
xiaoZhang
xiaoHua

List Data Manipulation

Our operations on variable data (for example, lists, databases, etc.) generally include four aspects: adding, deleting, modifying, and checking.

1. Add elements

There are several ways to add elements:

  1. appendAdd elements at the end
  2. insertInsert an element at the specified position
  3. extendmerge two lists

append

appendwill add the new element to the end of the list

# 定义变量A,默认有3个元素
A = ['xiaoWang','xiaoZhang','xiaoHua']

print("-----添加之前,列表A的数据-----A=%s" % A)

# 提示,并添加元素
temp = input('请输入要添加的学生姓名:')
A.append(temp)

print("-----添加之后,列表A的数据-----A=%s" % A)

insert

insert(index, object)Insert the element object before the specified position index

strs = ['a','b','m','s']
strs.insert(3,'h')
print(strs)  # ['a', 'b', 'm', 'h', 's']

extend

By extendadding elements from another collection to a list one by one

a = ['a','b','c']
b = ['d','e','f']
a.extend(b)
print(a)  # ['a', 'b', 'c', 'd', 'e', 'f'] 将 b 添加到 a 里
print(b)  # ['d','e','f'] b的内容不变

2. Modify elements

We access list elements by specifying a subscript, so when modifying an element, just assign a value to the specified list subscript.

# 定义变量A,默认有3个元素
A = ['xiaoWang','xiaoZhang','xiaoHua']

print("-----修改之前,列表A的数据-----A=%s" % A)

# 修改元素
A[1] = 'xiaoLu'

print("-----修改之后,列表A的数据-----A=%s" % A)

3. Find elements

The so-called search is to check whether the specified element exists, and to check the location of the element, which mainly includes the following methods:

  1. inandnot in
  2. indexandcount


The common method of searching in, not in Python is:

in(exists), if exists then the result is True, else is False
not in(does not exist), if not exists then the result is True, otherwiseFalse

# 待查找的列表
nameList = ['xiaoWang','xiaoZhang','xiaoHua']

# 获取用户要查找的名字
findName = input('请输入要查找的姓名:')

# 查找是否存在
if findName in nameList:
    print('在列表中找到了相同的名字')
else:
    print('没有找到')

Result 1: (found)

Result 2: (not found)

illustrate:

inAs long as the method can be used, not init is also used in the same way, but not inthe judgment is that it does not exist

index, count

indexIt is used to find the location of the element, and an error will be reported if it is not found; countit is used to count the number of occurrences of an element. They are used in the same way as in strings.

a = ['a', 'b', 'c', 'a', 'b']
a.index('a', 1, 3) # 注意是左闭右开区间
a.index('a', 1, 4)
a.count('b')
a.count('d')

4. Delete elements

It is analogous to real life, if a student transfers a class, then the name of the student after this entry should be deleted; this function of deleting is often used in development.

Common ways to delete list elements are:

  1. del: Delete according to subscript
  2. pop: delete the last element
  3. remove: Delete according to the value of the element

of the

movieName = ['加勒比海盗','骇客帝国','第一滴血','指环王','霍比特人','速度与激情']
print('------删除之前------movieName=%s' % movieName)
del movieName[2]
print('------删除之后------movieName=%s' % movieName)

pop

movieName = ['加勒比海盗','骇客帝国','第一滴血','指环王','霍比特人','速度与激情']
print('------删除之前------movieName=%s' % movieName)
movieName.pop()
print('------删除之后------movieName=%s' % movieName)

remove

movieName = ['加勒比海盗','骇客帝国','第一滴血','指环王','霍比特人','速度与激情']
print('------删除之前------movieName=%s' % movieName)
movieName.remove('指环王')
print('------删除之后------movieName=%s' % movieName)

5. Sorting (sort, reverse)

sortThe method is to rearrange the list in a specific order, the default is from small to large, and the parameters reverse=Truecan be changed to reverse order, from large to small.

reverseThe method is to reverse the list.

a = [1, 4, 2, 3]
a.reverse()  # 逆置,不排序
a.sort()  # 默认从小到大排序
a.sort(reverse=True)  # 从大到小排序

practise

Please remove words = ['hello','',','good','hi','','yes','','no']all empty strings in the list.

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

Graph prediction results with 4 regression methods: Vector Regression, Random Forest Regression, Linear Regression, K-Nearest Neighbors Regression

Guess you like

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