Python core technology and practical study notes (a)

1.1 concept

the same:

Most other programming languages ​​requires consistent set of data elements stored in types, but there is no such requirement python, lists and tuples are possibleStoring an ordered collection of any data type. (May also be nested within each other)

l = [1, 2, 'hello', 'world'] # 列表中同时含有 int 和 string 类型的元素
l
[1, 2, 'hello', 'world']

tup = ('jason', 22) # 元组中同时含有 int 和 string 类型的元素
tup
('jason', 22)

the difference:

  • List is dynamic, not a fixed length size can be increased freely, deletion or change elements (the mutable)
  • Tuple is static, the length of a fixed size, deletion or change can not be increased (the immutable)

If directly modify the elements of the tuple, it will error
if you want to modify elements of the tuple, you must also open up new tuple, copy add elements.

tup = (1, 2, 3, 4)
new_tup = tup + (5, ) # 创建新的元组 new_tup,并依次填充两个元组的值
new _tup
==========================
(1, 2, 3, 4, 5)

1.2 Operating

A negative index

Tuples and lists of support python negative index, i.e., the rearmost element of the list points to -1 / tuples, -2 to the penultimate, and so on.

Slicing

l = [1, 2, 3, 4]
l[1:3] # 返回列表中索引从 1 到 2 的子列表
==========================
[2, 3]

tup = (1, 2, 3, 4)
tup[1:3] # 返回元组中索引从 1 到 2 的子元组
==========================
(2, 3) 

It is noted that slicing and range (a, b), are closing the left and right open interval.

A list of tuples conversion

Lists and tuples can tuple () and list () conversion

list((1, 2, 3))
====================
[1, 2, 3]

tuple([1, 2, 3])
=====================
(1, 2, 3)

Built-in functions

l is a list, tup tuple

  1. l / tup.count(X): x number of statistics appear in a list or tuple
  2. l / tup.index(X): Returns the index at the first occurrence of x in a list or tuple
  3. the reversed () and sorted (): an inverted representation, or sort the list of tuples returned isNewly openedAfter the reversal, the sorted list or tuple (or tuples original list unchanged)
  4. l.sort () | l.reverse (): expressedListSitu sort, transpose (without the built-tuple, its place is not changed)

Differences 1.3 lists and tuples of storage

ListDynamic variable, TuplesStatic immutableSuch differences will certainly affect the storage of both.

Internal tuple list and are implemented in the form of array, since the variable list, it is an over-allocate the array, since the immutable tuple, the length of a fixed size.

Save for the same elements of lists and tuples l and tup, are:

l = [1, 2, 3]
l.__sizeof__()
64
tup = (1, 2, 3)
tup.__sizeof__()
48

List

Size of the list here more than 16 bytes tuples, for the following reasons:

  1. List is dynamic, needs to store a pointer to the corresponding element (here, int type, 8 bytes)
  2. Variable list, they need additional storage size has been allocated length (8 bytes), so as to track usage list space in a timely manner to allocate additional space is insufficient space

For a list of allocated extra space is insufficient disposable elements a plurality of spaces, i.e., over-allocating mechanism, which mechanism reduces the space allocated per deletions operation cost, ensure the efficiency, add or delete operations such as O (1)

l = []
l.__sizeof__() // 空列表的存储空间为 40 字节
40
l.append(1)
l.__sizeof__() 
72 // 加入了元素 1 之后,列表为其分配了可以存储 4 个元素的空间 (72 - 40)/8 = 4
l.append(2) 
l.__sizeof__()
72 // 由于之前分配了空间,所以加入元素 2,列表空间不变
l.append(3)
l.__sizeof__() 
72 // 同上
l.append(4)
l.__sizeof__() 
72 // 同上
l.append(5)
l.__sizeof__() 
104 // 加入元素 5 之后,列表的空间不足,所以又额外分配了可以存储 4 个元素的空间

Space on each additional allocation, the following rules:

0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...

Tuple

Tuples array as C language, is still immutable, and therefore storage space is fixed.

Performance 1.4 lists and tuples

From storage to see

Can be seen from the difference of both the storage, usage scenarios without considering the premise of tuples is more lightweight, it compares favorably to the list.

Look from the resource cache

python will be on in the backgroundStatic datado someResource Cache(Resource caching), such tuple, if it is not used and less space (less than 20), python will temporarily buffer section of memory (a cache within the free list).

The next time you need to define a tuple of equal size, the cache will be directly allocated memory space before, and no longer need to issue a request to allocate space to the operating system, which can greatly speed up the running speed of the program.

then,initializationLists and tuples of the same element, the latter is much faster;
however, forIndex Operations, Both almost the same.

1.5 lists and tuples usage scenarios

  1. If the amount of data and storage of the same, such as a direct function returns the latitude and longitude of the location, it directly to the front-end rendering, it is certainly more appropriate choice of tuples.
def get_location():
    ..... 
    return (longitude, latitude)
  1. If the data is stored or the number of changes, such as a log function on the social platform is a user browsing statistics of posts within a week, it is certainly more appropriate choice list.
viewer_owner_id_list = [] # 里面的每个元素记录了这个 viewer 一周内看过的所有 owner 的 id
records = queryDB(viewer_id) # 索引数据库,拿到某个 viewer 一周内的日志
for record in records:
    viewer_owner_id_list.append(record.id)

1.5 Questions

Create an empty list in the following two ways, which higher efficiency?

# 创建空列表
# option A
empty_list = list()

# option B
empty_list = []
  • list () is a function call, Python's function call creates a stack, and operates a series of parameters to check, more expensive
  • []Is aBuilt-in C function, It can be called directly, and therefore high efficiency

The course is a course on the platform geeks time, the quality is good, is Daniel, student party bought a few courses, but still feel a little expensive. . .
There is a need to sweep the two-dimensional code can attend the course, contact me (qq: 510650660) take my share and you split the bounty, hee hee hee
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/shichensuyu/article/details/92026249