Good article recommendation, transferred from CSDN, the original star StarDust
sequence
List (List) is a very important built-in data type in Python. The list consists of a series of elements, all tuples are enclosed in square brackets. After the list is created, you can add, delete, and modify operations.
The list can contain any Python data information, such as strings, numbers, lists, tuples, etc.
A list is an ordered collection with no fixed size and can store any number of Python objects of any type. The syntax is [element 1, element 2, ..., element n]
.
【example】
>>> list =[ “a”, “b”, “c” ]To define a list of characters.
>>> list =[1,2,3,4]To define a list of numbers.
>>> list =[[1,2,3,4],["a","b","c"]], The list of definition lists.
>>> list =[(1,2,3,4),("a","b","c")]To define a list of tuples.
>>> list((1,2))Convert a tuple into a list[1,2], list('test')Can put
String into['t','e','s','t']List
List notes:
All operations of the list are shown in the following table:
The operators of the list pairs + and * are similar to strings. The + sign is used for combined lists, and the * sign is used for repeated lists.
The slice operation (slice) can obtain a sublist (part of a list) from a list. We use a pair of square brackets, start offset start, end offset end, and optional step size step to define a slice.
Format: [start: end: step]
• [:] Extract the entire string from the beginning (default position 0) to the end (default position -1)
• [start:] Extract from start to the end
• [:end] Extract from the beginning to end-1
• [start: end] Extract from start to end-1
• [start: end: step] Extract from start to end-1, extract one character per step
• The position/offset of the first character on the left is 0, and the position/offset of the last character on the right is -1
【example】
>>> list =[1,2,3,4,5,6,7]>>> list[1:] #List after index 1---------[2,3,4,5,6,7]>>> list[:-1] #List index-Before 1-------[1,2,3,4,5,6]>>> list[1:3] #List index1到3之间的-----[2]>>> list[::-1]#[7,6,5,4,3,2,1] #Form the effect of the reverse function:
A. Assignment reference
a ={1:[1,2,3]}
b = a
print(id(a)==id(b))
Output:
True
Assignment reference, a and b both point to the same object.
B. Shallow copy
a ={1:[1,2,3]}
b = a.copy()print(id(a)==id(b))print(id(a[1])==id(b[1]))
Output:
False
True
a and b are independent objects, but their child objects still point to a unified object (reference).
C. Deep copy
import copy
a ={1:[1,2,3]}
b = copy.deepcopy(a)print(id(a)==id(b))print(id(a[1])==id(b[1]))print(id(a[1][0])==id(b[1][0]))
Output:
False
False
True
a and b completely copy the parent object and its children, and the two are completely independent. For a[1][0] and b[1][0], it is still a reference to object 1, and no new object is created. This conforms to the python storage mechanism.
Permanent sorting: sort()
list.sort(key=None, reverse=False)
Sort the original list.
key
-It is mainly used to compare the elements. There is only one parameter. The parameters of the specific function are taken from the iterable object and specify an element in the iterable object for sorting. reverse
-sorting rule, reverse = True
descending order, reverse = False
ascending order (default). This method has no return value, but it sorts the objects in the list.
Temporary sorting: sorted()
Python built-in functions,
Reverse sort: reverse()
【example】
>>> list1 =[3,5,1,6,9]>>> lsit2 =[3,5,1,6,9]>>> a = list1.sort() #Permanently sort, just this list will change
>>> print(a, l1)
# None [1,3,5,6,9]>>> b =sorted(list1) #Temporary sorting means that a variable can be assigned
>>> print(b, list1)
# [1,3,5,6,9][3,5,1,6,9]>>> c = list2.reverse()>>>print(c, list2)
# None [9,6,1,5,3]
list.append(object) Add an object object to the list
list.extend(sequence) adds the content of a sequence seq to the list
Python tuples are similar to lists. The difference is that tuples cannot be modified after they are created, similar to strings.
Unpack one-dimensional tuples (there are several elements left parenthesis define several variables)
【example】
( a, b, c)=(1,10.31,'python')print(a, b, c)
# 110.31 python
Decompress two-dimensional tuples (define variables according to the tuple structure in the tuple)
【example】
t =(1,10.31,('OK','python'))(a, b,(c, d))= t
print(a, b, c, d)
# 110.31 OK python
If you only want a few elements in the tuple, use the wildcard character "*", which is called wildcard in English, which represents one or more elements in computer language. The following example is to throw multiple elements to the rest
variable.
【example】
t =1,2,3,4,5
a, b,*rest, c = t
print(a, b, c) # 125print(rest) # [3,4]
If you don't care about the rest variable at all, then use wildcard "*" and underscore "_".
【example】
a, b,*_ = t
print(a, b) # 12
Definition of string:
A string is a collection of characters between quotation marks, where quotation marks include single quotation marks, double quotation marks, and triple quotation marks (three consecutive single quotation marks or double quotation marks).
【example】
>>> s1='I love Python'>>> s1
' I love Python'>>> s2=str([1,2,3])>>> s2
'[1, 2, 3]'
Python escape characters
Add u, r, b before the string
Python supports the output of formatted strings. Although very complicated expressions may be used in this way, the most basic usage is to insert a value into a string with the string format character %s. In Python, string formatting uses the same syntax as the sprintf function in C.
【example】
print "My name is %s and weight is %d kg!"%('Zara',21)
# My name is Zara and weight is 21 kg!
Python string formatting symbols:
Formatting operator auxiliary instructions:
Starting from Python2.6, a new string formatting function str.format() has been added, which enhances the function of string formatting.
【example】
>>>"{} {}". format("hello","world") #Do not set the specified location, follow the default order
' hello world'>>>"{0} {1}".format("hello","world") #Set the specified location
' hello world'>>>"{1} {0} {1}".format("hello","world") #Set the specified location
' world hello world'
print("Site name:{name},address{url}".format(name="Novice Tutorial", url="www.runoob.com"))
# Set parameters via dictionary
site ={"name":"Novice Tutorial","url":"www.runoob.com"}print("Site name:{name},address{url}".format(**site))
# Set parameters by list index
my_list =['Novice Tutorial','www.runoob.com']print("Site name:{0[0]},address{0[1]}".format(my_list)) # "0"It's required
Number formatting
^, <, > They are centered, left-justified, right-justified, followed by a width, and the character with padding after the: sign can only be one character. If it is not specified, it will be filled with spaces by default.
- Shows + before positive numbers,-before negative numbers; (space) means add spaces before positive numbers
b, d, o, and x are binary, decimal, octal, and hexadecimal, respectively.
【example】
>>> print("{:.2f}".format(3.1415926));3.14>>>print("{}The corresponding position is{{0}}".format("runoob"))
The location of runoob is{0}
Practice questions:
1、List manipulation exercise
The contents of the list lst are as follows
lst = [2, 5, 6, 7, 8, 9, 2, 9, 9]
Please write a program to complete the following operations:
>>> lst =[2,5,6,7,8,9,2,9,9]>>> lst.append(15)>>> lst.insert(5,20)>>> lst.extend([2,5,6])>>> del lst[3]>>> lst.reverse()>>> lst.sort()>>> lst.sort(reverse=True)
Original address
https://blog.csdn.net/OuDiShenmiss/article/details/107599379
Love&Share [Finish]
Recommended Posts