current position:Home>Python notes (6): definition and use of lists
Python notes (6): definition and use of lists
2022-01-30 10:41:29 【A bowl week】
Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .
Hello everyone , I am a A bowl week , One doesn't want to be drunk ( Internal volume ) The front end of the . If you are lucky enough to get your favor , I'm very lucky ~
Define and use lists
stay Python in , A list is a data structure composed of a series of elements in a specific order , In other words, variables of list type can Store multiple data , And Can be repeated .
Definition list
-
Use
[]
Literal syntax defines variables , Multiple elements in the list use commas,
Segmentation , The sample code is as follows :list1 = ["Hello", " A bowl week ", " Hello "] list2 = [1, 2, 3, 4, 5] print(list1) # ['Hello', ' A bowl week ', ' Hello '] print(list2) # [1, 2, 3, 4,5] Copy code
-
Use Python Built in
list
Program other sequences into a list , The sample code is as follows :list1 = list(range(10)) list2 = list("hello") print(list1) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(list2) # ['h', 'e', 'l', 'l', 'o'] Copy code
A list is a variable data type , That is, the elements of the list can be modified , This is significantly different from string , After modifying the string type , Will return a new string
Access the values in the list
If you access a value in the list , Use the subscript index to access the values in the list , Like a string, use square brackets to intercept characters , The sample code is as follows :
list1 = ["Hello", " A bowl week ", " Hello "]
# Index of the list
print(list1[1]) # A bowl week
# Slice of the list
print(list1[1:3]) # [' A bowl week ', ' Hello ']
Copy code
List operators
List and string types are the same , It also supports splicing 、 repeat 、 Member operation and other operations , The sample code is as follows :
list1 = ["Hello"]
list2 = ["World"]
list3 = [1, 2, 3, 4, 5]
list4 = list(range(1, 6))
list5 = list1 + list2 # ['Hello', 'World']
print(list5)
list6 = list1 * 3 # ['Hello', 'Hello', 'Hello']
list7 = list3 * 2 # [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
print(list6)
print(list7)
print("W" in list1) # False
print("W" in list2) # False
# List comparison operation
# The equality ratio of two lists is whether the elements at the corresponding index position are equal
print(list3 == list4) # True
list8 = list(range(1, 7))
print(list3 == list8) # False
Copy code
Traversal of list elements
Traversing a list is the same as traversing a string , The sample code is as follows :
list1 = ["H", "e", "l", "l", "o"]
# Method 1
for index in range(len(list1)):
print(list1[index])
# Method 2
for ch in list1:
print(ch)
Copy code
List method
Add and remove elements
Go straight to the code
list1 = ["cute", "beautiful", " A bowl week "]
# append() Add elements to the end of the list
list1.append("lovely")
print(list1) # ['cute', 'beautiful', ' A bowl week ', 'lovely']
# insert() Inserts an element at the specified index position in the list
list1.insert(2, "prefect")
print(list1) # ['cute', 'beautiful', 'prefect', ' A bowl week ', 'lovely']
# remove() Deletes the specified element
list1.remove("lovely")
print(list1) # ['cute', 'beautiful', 'prefect', ' A bowl week ']
# pop() Delete the element at the specified index location
list1.pop(2)
print(list1) # ['cute', 'beautiful', ' A bowl week ']
# clear() Empty the list of elements
list1.clear()
print(list1) # []
Copy code
stay Python Can also be used in del
Keyword to delete a list element , Be similar to pop
, Sample code ↓
list1 = ["cute", "beautiful", " Sweet "]
del list1[1]
print(list1) # ['cute', ' Sweet ']
# Delete the entire list
del list1
print(list1) # NameError: name 'list1' is not defined
Copy code
Element position and number
Use index()
To find the location of the element , Use count()
To count the number of occurrences of elements
list1 = ["beautiful", "cute", "beautiful",
'prefect', "beautiful", " A bowl week ", 'lovely']
# lookup "beautiful" First occurrence
print(list1.index("beautiful")) # 0
# Find... After the fourth element "beautiful" The location of the last occurrence
print(list1.index("beautiful", 3)) # 4
# Statistics "beautiful" Number of occurrences
print(list1.count("beautiful")) # 3
Copy code
Element sorting and inversion
Use sort()
Method can realize the sorting of list elements , and reverse()
Method can realize the inversion of elements , Sample code ↓
list1 = ["cute", "beautiful", " A bowl week "]
list2 = list(range(10))
# Sort
list1.sort()
print(list1) # ['beautiful', 'cute', ' A bowl week ']
# reverse
list1.reverse()
print(list1) # [' A bowl week ', 'cute', 'beautiful']
list2.reverse()
print(list2) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# The previous operation is to modify the original list , If you don't let the original data be destroyed, you can use copy() Make a backup
list3 = list2.copy()
list3.sort()
print(list2) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
print(list3) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy code
summary
Method | describe | Parameters |
---|---|---|
append() |
Add a new object at the end of the list | Objects added to the end of the list . |
insert() |
Used to insert the specified object into the specified location of the list | index -- object obj Index location to insert . obj -- To insert an object in the list . |
remove() |
Function to remove the first match of a value in the list . | Objects to be removed from the list . |
pop() |
Function to remove an element from the list ( Default last element ) | Optional parameters , To remove the index value of a list element , Cannot exceed the total length of the list , The default is index=-1, Delete the last list value . |
clear() |
Function to clear the list | nothing |
index() |
Used to find the index position of the first match of a value from the list . | x-- Objects found . start-- Optional , The starting point of the search . end-- Optional , End of search . |
count() |
Used to count the number of times an element appears in the list . | Statistical objects in the list . |
sort() |
Used to sort the original list | key -- It's basically a comparison element reverse -- Sort rule ,reverse = True Descending , reverse = False Ascending ( Default ) |
reverse() |
For elements in the reverse list | nothing |
copy() |
Used to copy lists | nothing |
The generative expression of the list
requirement : For the string 123
And string ABC
Create a list of Cartesian Products , The sample code is as follows :
Original method
a = "123"
b = "ABC"
list1 = []
for x in a:
for y in b:
list1.append(x + y)
print(list1) # ['1A', '1B', '1C', '2A', '2B', '2C', '3A', '3B', '3C']
Copy code
Generate column method
a = "123"
b = "ABC"
list1 = [x + y for x in a for y in b]
print(list1) # ['1A', '1B', '1C', '2A', '2B', '2C', '3A', '3B', '3C']
Copy code
This method not only has a small amount of code , And the performance is better than ordinary
for
Circulation andappend
Additional way
nested list
Because the variables in the list can store multiple data types , When there is a list in the list , This is called the nesting of lists , The sample code is as follows :
list1 = [["cute", "beautiful", " A bowl week "], "cute", "beautiful", " A bowl week "]
print(list1[0]) # ['cute', 'beautiful', ' A bowl week ']
print(list1[1]) # cute
# The one you want to see nested cute You need to use multiple index values
print(list1[0][0]) # cute
Copy code
The same is true no matter how many nested
copyright notice
author[A bowl week],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301041254169.html
The sidebar is recommended
- Similarities and differences of five pandas combinatorial functions
- Python beginner's eighth day ()
- Necessary knowledge of Python: take you to learn regular expressions from zero
- Get your girlfriend's chat records with Python and solve the paranoia with one move
- My new book "Python 3 web crawler development practice (Second Edition)" has been recommended by the father of Python!
- From zero to familiarity, it will take you to master the use of Python len() function
- Python type hint type annotation guide
- leetcode 108. Convert Sorted Array to Binary Search Tree(python)
- For the geometric transformation of Python OpenCV image, let's first talk about the extraordinary resize function
- leetcode 701. Insert into a Binary Search Tree (python)
guess what you like
-
For another 3 days, I sorted out 80 Python datetime examples, which must be collected!
-
Python crawler actual combat | using multithreading to crawl lol HD Wallpaper
-
Complete a python game in 28 minutes, "customer service play over the president card"
-
The universal Python praise machine (commonly known as the brushing machine) in the whole network. Do you want to know the principle? After reading this article, you can write one yourself
-
How does Python compare file differences between two paths
-
Common OS operations for Python
-
[Python data structure series] linear table - explanation of knowledge points + code implementation
-
How Python parses web pages using BS4
-
How do Python Network requests pass parameters
-
Python core programming - decorator
Random recommended
- Python Network Programming -- create a simple UPD socket to realize mutual communication between two processes
- leetcode 110. Balanced Binary Tree(python)
- Django uses Django celery beat to dynamically add scheduled tasks
- The bear child said "you haven't seen Altman" and hurriedly studied it in Python. Unexpectedly
- Optimization iteration of nearest neighbor interpolation and bilinear interpolation algorithm for Python OpenCV image
- Bilinear interpolation algorithm for Python OpenCV image, the most detailed algorithm description in the whole network
- Use of Python partial()
- Python game development, pyGame module, python implementation of angry birds
- leetcode 1104. Path In Zigzag Labelled Binary Tree(python)
- Save time and effort. 10 lines of Python code automatically clean up duplicate files in the computer
- Learn python, know more meat, and be a "meat expert" in the technical circle. One article is enough
- [Python data structure series] "stack (sequential stack and chain stack)" -- Explanation of knowledge points + code implementation
- Datetime module of Python time series
- Python encrypts and decrypts des to solve the problem of inconsistency with Java results
- Chapter 1: introduction to Python programming-4 Hello World
- Summary of Python technical points
- 11.5K Star! An open source Python static type checking Library
- Chapter 2: Fundamentals of python-1 grammar
- [Python daily homework] day4: write a function to count the number of occurrences of each number in the incoming list and return the corresponding dictionary.
- Python uses turtle to express white
- Some people say Python does not support function overloading?
- "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system with Python
- Introduction to Python - CONDA common commands
- Python actual combat | just "4 steps" to get started with web crawler (with benefits)
- Don't know what to eat every day? Python to tell you! Generate recipes and don't worry about what to eat every day!
- Are people who like drinking tea successful? I use Python to make a tea guide! Do you like it?
- I took 100g pictures offline overnight with Python just to prevent the website from disappearing
- Binary operation of Python OpenCV image re learning and image smoothing (convolution processing)
- Analysis of Python event mechanism
- Iterator of Python basic language
- Base64 encryption and decryption in Python
- Chapter 2: Fundamentals of python-2 variable
- Python garbage collection summary
- Python game development, pyGame module, python takes you to realize a magic tower game from scratch (1)
- Python draws a spinning windmill with turtle
- Deep understanding of Python features
- A website full of temptations for Python crawler writers, "lovely picture network", look at the name of this website
- Python opencv Canny edge detection knowledge supplement
- Complex learning of Python opencv Sobel operator, ScHARR operator and Laplacian operator
- Python: faker extension package