Python study notes (10)--combined data types (sequence types)

A sequence is a set of data with a sequential relationship. It is a one-dimensional element vector. The element types can be different. Similar to a sequence of mathematical elements, the elements are guided by serial numbers, and specific elements of the sequence are accessed through subscripts. Sequence type is a base class type, string type, tuple type, list type are all sequence types.

Sequence number definition, increasing the sequence number in the forward direction, and decreasing the sequence number in the reverse direction. A[0]-A[5] A[-6] - A[-1]

Sequence type operations:

x in S
x not in S
s+t
s *n or n* s
s[i]
s[i:j:k] or s[i:j]
s[:: - 1 ] reverse sequence
Sequence type functions and methods:
len (s)
min (s)
max(s)
s.index(x)或s.index(x,i,j)
s.count(x) the number of times x appears in s

Tuple type:

A tuple is a sequence type. Once created, it cannot be modified. It is created using parentheses () or tuple(). The elements are separated by commas. Parentheses can be used or not. For example, return 1,2 returns a tuple. Group type.

>>> createtur="cat","dog","tiger"
>>> createtur
('cat', 'dog', 'tiger')
>>> color=(122,createtur,"blue")
>>> color
(122, ('cat', 'dog', 'tiger'), 'blue')
>>> color[-2][2]
'tiger'

The element type integrates all the general operations of the sequence type and cannot be modified after creation.

List type:

A list is an extension of a sequence type that can be modified at will after creation. Use square brackets [], or list creation, elements are separated by commas, element types can be different, and the list has no length limit. List assignment is just a list with a different name, but the same memory location, similar to a pointer.

>>> ls=["cat","dog","tiger",1024]
>>> ls[1:2]=[1,2,3,4]
>>> ls
['cat', 1, 2, 3, 4, 'tiger', 1024]
>>> del ls[::3]
>>> ls
[1, 2, 4, 'tiger']
>>> ls*2
[1, 2, 4, 'tiger', 1, 2, 4, 'tiger']

ls.append(x) adds an element x at the end of ls

ls.clear() removes all elements in the list

ls.copy() generates a new list and assigns all elements in ls

ls.insert(i,x) insert x at the ith position

ls.pop(i) removes the i-th element in the list and deletes the element

ls.remove(x) removes the first element x that appears in the list

ls.reverse() reverses the elements in a list

del ls [i] Someone del ls [i: j: k]

Sequence type application scenarios:

A representation of a set of data, traversed. for item in ls: for item in tp:

If you don't want the data to be changed by the program, you can convert it to a tuple type.

>>> ls =[1,2,3,4,5]
>>> lt=tuple(ls)
>>> lt
(1, 2, 3, 4, 5)

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325255577&siteId=291194637