程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

List of Python

編輯:Python

python list

author:Once Day date:2022 year 2 month 16 Japan

The purpose of this document is to summarize the relevant contents , Scattered knowledge is difficult to remember and learn .

This document is based on windows platform .

View a full range of documents :python Basics _CSDN Blog .

List of articles

      • python list
        • 1. brief introduction
        • 2. Create a list of
        • 3. List basic operations
          • 3.1 Access an element
          • 3.2 section
          • 3.3 Add up
          • 3.4 Multiply
          • 3.5 Membership
          • 3.6 Iteration list
          • 3.7 Modify the value of an element
          • 3.8 Remove elements
          • 3.9 Common built-in functions
          • 3.10 Multidimensional list
        • 4. Tabular method
          • 4.1 append Add a new object at the end of the list
          • 4.2 clear clear list , Become an empty list
          • 4.3 copy Copy list
          • 4.4 count Count the number of times an element appears in a list
          • 4.5 extend Splice two sequences
          • 4.6 index Find the index position of the first match of a value in the list
          • 4.7 insert Insert objects into the list
          • 4.8 pop Removes an element from the list ( Default last element ), And returns the value of that element
          • 4.9 remove Removes the first match of a value in the list
          • 4.10 reverse Reverse list of elements
          • 4.11 sort Sort the original list in place
        • notes : The content of this article is collected and summarized on the Internet , For learning only !

1. brief introduction

The list is Python One of the most basic and commonly used data structures in . Each element in the list is assigned a number as an index , Used to indicate the position of the element in the list . The index of the first element is 0, The second index is 1, And so on .

Python The list is an ordered and repeatable collection of elements , Can be nested 、 iteration 、 modify 、 Fragmentation 、 Additional 、 Delete , Member judgment .

From a data structure point of view ,Python The list of is a generalized table , And each location holds a pointer to the object .

Python It also supports negative index values , This kind of index counts right to left , let me put it another way , Count from the last element , From index value -1 Start .

2. Create a list of

nonelist=[] # An empty list 
numbers=[1,2,3,4,5,6] # list 
mylist=[1,'b',[1,5],'ssdd'] # The list can be inlaid , And other data objects .

The elements in the list , It can be any other type of data , Multi level nested list , The number of elements is unlimited .

The list can be modified , But tuples and strings cannot be modified .

3. List basic operations

3.1 Access an element
>>> s=['h','e','l','l','o',',','w','o','r','l','d','!']
>>> s[1]
'e' # The first element is the index value 0
>>> s[-1]
'!' # Minus sign from right to left .
>>> s[12]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range # Accessing beyond the index value will throw an exception 
3.2 section

Accessing elements in a specific scope , Slicing does not modify the original list , You can save the result to a new variable , Therefore, slicing is also a safe operation , It is often used to copy a list .

>>> n=[1,2,3,4,5,6,7,8,9]
>>> n[2:4]
[3,4] # The first index specifies the start ( Be included in ), The second index specifies the end , Not to be included .
>>> n[7:9]
[8,9] # Include the last element with the imaginary tenth element .
>>> n[-3:-1]
[7,8] # You can use plural indexes .
>>> n[-3:0]
[] # Empty sequence , The second index should follow the first index .
>>> n[-3:]
[7,8,9] # Omit the second sequence , All the following elements are included by default 
>>> n[:2]
[1,2] # Omit the first index , All the previous elements are included by default , Note that the last index is not included 
>>> n[:]
[1,2,3,4,5,6,7,8,9] # Contains all elements 
# Change the step size , The default is 1.
>>> n[0:9:2]
[1,3,5,7,9] # In steps of 2, Take one from every other number .
>>> n[9:0:-2]
[8,6,4,2] # Extract elements from right to left , The first index is larger than the second index , But the step size is negative , So it can run 
>>> n[::-2]
[8,6,4,2] # It can also be successful !!!
3.3 Add up

use + Connect Same type Sequence !

>>> [1,2,3]+[4,5,6]
[1,2,3,4,5,6]
3.4 Multiply

Repetitive sequence N Time

>>> [12]*5
[12,12,12,12,12]
>>> [None]*3
[None,None,None] # Nothing there? -None
3.5 Membership

in Operator , Boolean operator , return True or False

>>> s=['h','e','l','l','o',',','w','o','r','l','d','!']
>>> 'h' in s
True
3.6 Iteration list
>>> for x in [1, 2, 3]: print(x)
1
2
3
3.7 Modify the value of an element

Index assignment

>>> nums=[1,2,3,4,5]
>>> nums[2]=8 # You can't assign a value to an element that doesn't exist ( Otherwise, the report will be wrong )
>>> nums
[1,2,8,4,5]

Slice assignment
The step size is not 1 The number of elements should be considered to match

>>> name=list("onceday")
['o','n','c','e','d','a','y'] # May by list Function directly creates 
>>> name[4:]=list('DAY')
['o','n','c','e','D','A','Y'] # On the index 5 To the end of the value assignment 
# You can change the length of the list 
>>> name[4:]=list('d')
['o','n','c','e','d']
# You can insert elements 
>>> name[1:1]=list("eeee")
['o','e','e','e','e','n','c','e','d']
# You can also clear elements 
>>> name[1:5]=[]
name=['o','n','c','e','d']

The step size is not 1 The slice assignment of can also be performed , Including negative numbers

3.8 Remove elements

Use del sentence

>>> names=['asd','zxc','qwe']
>>> del names[1]
['asd','qwe']
3.9 Common built-in functions
  • len(list) Returns the number of list elements , That is, get the length of the list
  • max(list) Returns the maximum value of a list element
  • min(list) Returns the minimum value of a list element
  • list(seq) Convert sequence to list

None of these operations will modify the list itself , It belongs to safe operation .max、min stay Python3 in , You can't compare the sizes of different types of objects .

3.10 Multidimensional list

Lists can nest lists , Form a multidimensional list , Shaped like a matrix . The reference method of its element is list[i][j][k]…. Of course , You can also nest other data types .

>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> a[0][1]
2
>>> a = [[1,2,3],[4,5,6],[7,8,9],{
"k1":"v1"}]
>>> a[3]["k1"]
'v1'

4. Tabular method

4.1 append Add a new object at the end of the list
nums=[1,2,3,4,5,6]
nums.append(4) # hold 4 Add to the end of the list 
#nums=[1,2,3,4,5,6,4]
4.2 clear clear list , Become an empty list
nums.clear() # clear list 
#nums=[]
4.3 copy Copy list
a=[1,2,3,4]
b=a # Regular replication simply b Associated to the same storage space 
b[1]=4
#a=[1,4,3,4] a The value in has also changed 
c=[1,2,3]
d=c.copy() # A copy will be created 
d[1]=4
#c=[1,2,3] # here c The value in has not changed 
#d=[1,4,3] 
4.4 count Count the number of times an element appears in a list
['aa','ss','dd','cc','aa'].count('aa') # Calculates how many times the specified element appears .
#2 Time 
4.5 extend Splice two sequences
e=[1,2,3]
f=[4,5,6]
e.extend(f) # Append multiple values to the end of the list 
#e=[1,2,3,4,5,6]
e=e+f # Splicing , A new copy will be created , Low efficiency .
a[len(a):]=b # Slice assignment , Effect and extend identical .
4.6 index Find the index position of the first match of a value in the list
string=['aa','dd','ff','ss','aa']
string.index('aa') # Find the index of the first occurrence of the specified value in the list 
#0, If there is no element to search , May be an error .
4.7 insert Insert objects into the list
numbers[1,2,3,4,5,6]
numbers.insert(2,'right') # Insert an object into the list 
#numbers=[1,2,'right',3,4,5,6]
numbers[2:2]=['right'] # Effect and insert identical 
4.8 pop Removes an element from the list ( Default last element ), And returns the value of that element
x=[1,2,3]
x.pop() # Delete the last element , And return this element 
x.pop(0) # Delete the first 1 Elements , And return this value .
#pop and append Stack can be built , Last in, first out (LIFO), fifo (FIFO)
4.9 remove Removes the first match of a value in the list
x=['a','s','d','a']
x.remove('a') # Delete the first element with the specified value , No return value 
# x=['s','d','a']
# Delete unknown element ( Not in the list ) Will be an error .
4.10 reverse Reverse list of elements
x=[1,2,3,4]
x.reverse() # Arrange the elements in the list in reverse order 
#x=[4,3,2,1]
4.11 sort Sort the original list in place
x=[2,1,5,3,4]
x.sort() # Sort the list in place , No return value 
#x=[1,2,3,4,5]
# Keep the original list , And save the sorted list to a new list 
x=[2,1,3]
y=x.copy()
y.sort()
#x=[2,1,3]
#y=[1,2,3]
x=[3,2,1,4,5]
y=sorted(x) # Return a sequence 
#x=[3,2,1,4,5]
#y=[1,2,3,4,5]
#sort and sorted Acceptable parameters key and reverse, Not for the time being 

notes : The content of this article is collected and summarized on the Internet , For learning only !


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved