Unit overview
Mainly solve the problem: let the program handle a set of data better
Three types of important combination data types: collection type, sequence type and dictionary type
After studying this chapter, we can build patterns of sets, sequences and dictionaries in our minds to express and process a set of data
1. Definition
A sequence is a set of elements with a sequential relationship
-the sequence is a one-dimensional element vector, the elements can be the same, the element type can be different
-similar to the mathematical element sequence: S0, S1,..., Sn
-the elements are guided by the sequence number, and can be accessed by subscripts Specific element
Sequence is a base type, generally not used directly.
Its derived types: string type, tuple type, list type
There are two numbering systems
2. Sequence processing functions and methods
① Six general operators
例
ls = ["python",123,".io"]
print(ls[::-1])
输出
['.io', 123, 'python']
② Five functions and methods
例
ls = ["python",123,".io"]
print(len(ls))
s = "python123.io"
print(max(s))
输出
3
y//最大字母序
3. Tuple types and operations
Tuples are an extension of sequence types, and are characterized once they are created and cannot be modified.
Means: use () or tuple() to create, separated by commas
Parentheses are optional when used
例1
def func():
return 1,2
这里虽返回了两个值,但在python内部认为是一个元组类型值
例2
creature = "dog","cat","tiger","human"
print(creature)
输出
('dog', 'cat', 'tiger', 'human')
例3
color = (0x001100,"blue",creature)
print(color)
输出
(4352, 'blue', ('dog', 'cat', 'tiger', 'human'))
Tuple type inherits all common operations of sequence type, no special operations
例
print(color[-1][1])
输出
cat
4. List types and operations
List is an extension of sequence type, very commonly used, and can be modified at will after creation
Use [] or list() to create, separated by commas
The types of elements in the list can be different, and the length is unlimited
例
ls = ["cat","dog","yoyo",123]
lt = ls
注:此处lt和ls仍指向同一个列表,相当于起了个别名
Operation functions and methods
例
ls = ["cat","dog","yoyo",123]
ls[1:2] = [1,2,3,4]
print(ls)
输出
['cat', 1, 2, 3, 4, 'yoyo', 123]
例
del ls[::3]
print(ls)
输出
[1, 2, 4, 'yoyo']
例
print(ls*2)
输出
[1, 2, 4, 'yoyo', 1, 2, 4, 'yoyo']
- Sequence type application scenario
① Data representation, which means a set of ordered data, and then manipulate them
-tuples are used in application scenarios where the elements do not change, and more used in fixed collocation scenarios (such as function return values)
-lists are more flexible, Is the more commonly used sequence type
Element traversal
for item in ls (list):
<statement block>
for item in tp (tuple):
<statement block>
② Data protection
If you don’t want the data to be modified, convert it to a tuple type
例
ls = ["cat","dog","yoyo",123]
lt = tuple(ls)
print(lt)
输出
('cat', 'dog', 'yoyo', 123)
Source: BIT Python MOOC