python linear data structure
<center>码好python的每一篇文章.</center>
A linear data structure
Linear structure of this chapter to introduce: list, tuple, string, bytes, bytearray.
-
Linear table: an abstract mathematical concepts, is a set of abstract element sequence, elements of a finite number (0 or any number).
Table can be divided into a linear sequence table and link table.
-
Table order: an ordered set of elements stored in memory. In list is a typical sequence table.
-
Linked table: a set of elements stored in memory disperse link up with each other to know who connected Yes.
For both carried tables, elements in the array to find, add, delete, modify, and see what effect:
-
Finding Elements
For the sequence table is ordered data stored in memory element can be quickly acquired by an index number, and high efficiency. .
For the linked table is dispersed storage, only through one iteration to get the elements, poor efficiency.
-
Add elements
For sequential table, if the element is added at the end, no impact on the entire data tables, but the element is inserted at the beginning or the middle, all the elements have to reorder the back of the large (think millions or greater impact The amount of data).
For the linked table, regardless of where the added elements will not affect other elements, small impact.
-
Removing elements
for the order table, delete elements and adding elements has the same problem.
For the linked table, no matter where you remove elements without affecting other elements, small impact. -
Modify elements
for the sequence table, indexed by the elements can quickly access and modify high efficiency.For the linked table, and then can only be modified by an iterative get the elements and inefficient.
Summary: Find a sequence table for the highest efficiency and modify, add and remove inefficient. Linked table opposite.
2. The built-in data types used
2.1 Numeric
-
int type integer
Description : Integer negative integers including 0, a positive integer (... -2, -1,0,1,2, ...).
x1 = 1 x2 = 0 x3 = -1 print(type(x1), x1) print(type(x2), x2) print(type(x3), x3) # 输出结果如下: <class 'int'> 1 <class 'int'> 0 <class 'int'> -1
int () method: numeric or string may be converted to an integer, the default base = 10, 10 represents a decimal and parameter passing 0 is returned.
x1 = int() x2 = int('1') x3 = int('0b10',base=2) #base=2,表二进制,与传入参数类型一致。 x4 = int(3.14) print(type(x1), x1) print(type(x2), x2) print(type(x3), x3) print(type(x4), x4) # 输出结果如下: <class 'int'> 0 <class 'int'> 1 <class 'int'> 2 <class 'int'> 3
-
floating point type float
Description : composition of the integer and fractional part, may be passed parametersint
,str
,bytes
,bytearray
.x1 = float(1) x2 = float('2') x3 = float(b'3') print(type(x1), x1) print(type(x2), x2) print(type(x3), x3) # 输出结果如下: <class 'float'> 1.0 <class 'float'> 2.0 <class 'float'> 3.0
-
complex (complex type)
Description : the real and imaginary number part composition, all floating point numbers.
Parameter can be passed
int
,str
if two parameters passed in front of one of the real part and the imaginary part as a parameter.x1 = complex(1) x2 = complex(2,2) x3 = complex('3') print(type(x1), x1) print(type(x2), x2) print(type(x3), x3) # 输出结果如下: <class 'complex'> (1+0j) <class 'complex'> (2+2j) <class 'complex'> (3+0j)
-
bool (Boolean)
Description : int subclass and returns True and False, corresponding to 0 and 1.
x1 = bool(0) x2 = bool(1) x3 = bool() x4 = 2 > 1 print(type(x1), x1) print(type(x2), x2) print(type(x3), x3) print(type(x4), x4) # 输出结果如下: <class 'bool'> False <class 'bool'> True <class 'bool'> False <class 'bool'> True
2.2 sequence (sequence)
2.2.1 list list
Description: List element consists of several objects, and a 有序可变
linear data structure, the use of parentheses [ ]
represents.
-
initialization
lst = [] # 空列表方式1 #或者 lst = list() # 空列表方式2 print(type(lst),lst) # 输入结果如下: <class 'list'> []
-
index
Description: Use positive index (from left to right), a negative index (right to left) to access elements, time complexity
O(1)
, high efficiency use.According to the given interval to obtain data, called slices.
Positive index:
From left to right, starting from 0 index interval [0, L -1], does not include the left and right bag.
lst = ['a','b','c','d'] print(lst[0]) # 获取第一个元素 print(lst[1:2]) # 获取第二个元素,左包右不包,切片 print(lst[2:]) # 获取第三个元素到最后一个元素,切片 print(lst[:]) # 获取所有元素,切片 # 输出结果如下: a ['c'] ['c', 'd'] ['a', 'b', 'c', 'd']
Negative Index:
From right to left, start index from -1, interval [- length -1]
lst = ['a','b','c','d'] print(lst[-1]) print(lst[-2:]) # 输出结果如下: d ['c', 'd']
-
Inquire
index () method:
L.index(value, [start, [stop]]) -> integer
Returns the index id, to iterate over the list, time complexity is O (n).
lst = ['a','b','c','d'] print(lst.index('a',0,4)) # 获取区间[0,4]的元素'a'的索引id # 输出结果如下: 0
Note: If you can not find an element is thrown
ValueError
.count( ) 方法:L.count(value) -> integer
Returns the number of elements appear to iterate over the list, time complexity is O (n).
lst = ['a','b','a','b'] print(lst.count('a')) # 输出结果如下: 2
len () method: returns the number of elements of the list, the time complexity is O (1).
lst = ['a','b','c','d'] print(len(lst)) # 输出结果如下: 4
Note: The so-called O (n) refers to the size of the data as increasing the efficiency decreased, while the O (1), by contrast, is not as big data scale to be efficient.
-
modify
List is an ordered variable, it is possible to modify the elements in the list.
lst = ['a','b','c','d'] lst[0] = 'A' print(lst) # 输出结果如下: ['A', 'b', 'c', 'd']
-
increase
append () method:
L.append(object) -> None
Additional elements of the tail, in situ modification, return None.
lst = ['a','b','c','d'] lst.append('e') print(lst) # 输出结果如下: ['a', 'b', 'c', 'd', 'e']
insert () method:
L.insert(index, object) -> None
,Insert element object in the specified index, return None.
lst = ['a','b','c','d'] lst.insert(0,'A') # 在索引0位置插入'A',原有的元素全部往后移,增加了复杂度 print(lst) # 输出结果如下: ['A', 'a', 'b', 'c', 'd']
extend () method:
L.extend(iterable) -> None
A plurality of elements can be increased, the objects may be elements of additional iteration into the return None.
lst = ['a','b','c','d'] lst.extend([1,2,3]) print(lst) # 输出结果如下: ['a', 'b', 'c', 'd', 1, 2, 3]
You can also list through
+
and*
, spliced into the new list.lst1 = ['a','b','c','d'] lst2 = ['e','f','g'] print(lst1 + lst2) print(lst1 * 2) # 将列表里面的元素各复制2份 # 输出结果如下: ['a', 'b', 'c', 'd', 'e', 'f', 'g'] ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']
There is also a special attention to the situation as follows:
lst1 = [[1]] * 3 # 结果:[[1], [1], [1]] print(lst1) lst1[0][0] = 10 # 结果:[[10], [1], [1]],是这样嘛?? print(lst1) # 输出结果如下: [[1], [1], [1]] [[10], [10], [10]] # 为什么结果会是这个?请往下看列表复制章节,找答案!
-
delete
remove () method:
L.remove(value) -> None
Traversing from left to right to find, to find the deleted element, returns None, not found is thrown
ValueError
.lst = ['a','b','c','d'] lst.remove('d') print(lst) # 输出结果如下: ['a', 'b', 'c'] # 元素'd'已经被删除
pop () method:
L.pop([index]) -> item
Default delete trailing elements, remove elements to specify the index, the index is thrown out of bounds
IndexError
.lst = ['a','b','c','d'] lst.pop() print(lst) # 输出结果如下: ['a', 'b', 'c']
clear () method:
L.clear() -> None
Empty list of all the elements of caution.
lst = ['a','b','c','d'] lst.clear() print(lst) # 输出结果如下: [] # 空列表了
-
Reverse
reverse () method:
L.reverse()
The elements in the list reversal, return None.
lst = ['a','b','c','d'] lst.reverse() print(lst) # 输出结果如下: ['d', 'c', 'b', 'a']
-
Sequence
sort () method:
L.sort(key=None, reverse=False) -> None
Sort the elements of the list, the default is ascending order, reverse = True descending.
lst = ['a','b','c','d'] lst.sort(reverse=True) print(lst) # 输出结果如下: ['d', 'c', 'b', 'a']
-
in Member operation
Determine whether the members on the list inside, then returns True, no return False.
lst = ['a','b','c','d'] print('a' in lst) print('e' in lst) # 输出结果如下: True False
-
Copy List
Description: copy the list refers to the list of copied elements, it can be divided into deep and shallow copy copy two kinds. List elements objects such as lists, tuples, dictionaries, classes, instances of these classified as a reference type (refer to memory addresses), and numbers, strings, first classified as a simple type, so that we can understand.
Example 1: This is the copy belonging Well?
lst1 = [1,[2,3],4] lst2 = lst1 print(id(lst1),id(lst2),lst1 == lst2, lst2) # id() 查看内存地址 # 输出结果如下: 1593751168840 1593751168840 True [1, [2, 3], 4]
Obviously not belong to any copy, saying that white is point to the same memory address.
Example Two: shallow copy copy
Description: shallow copy for
引用类型
the object is not a copy, pointing to the address is still the same.lst1 = [1,[2,3],4] lst2 = lst1.copy() print(id(lst1),id(lst2),lst1 == lst2, lst2) print('=' * 30) lst1[1][0] = 200 # 修改列表的引用类型,所有列表都会改变 print(lst1, lst2) # 输出结果如下: 1922175854408 1922175854344 True [1, [2, 3], 4] ============================== [1, [200, 3], 4] [1, [200, 3], 4]
Example Three: deep copy deepcopy
Description: deep copy for
引用类型
an object will copy into another one, the address is not the same point.import copy lst1 = [1,[2,3],4] lst2 = copy.deepcopy(lst1) print(id(lst1),id(lst2),lst1 == lst2, lst2) print('=' * 30) lst1[1][0] = 200 # 修改列表的引用类型,不会影响其他列表 print(lst1, lst2) # 输出结果如下: 2378580158344 2378580158280 True [1, [2, 3], 4] ============================== [1, [200, 3], 4] [1, [2, 3], 4]
2.2.2 tuple tuple
Description: tuple element is composed of several objects, and a 有序不可变
data structure, use parentheses ( )
represent.
-
initialization
t1 = () # 空元素方式1,一旦创建将不可改变 t2 = tuple() # 空元素方式2,一旦创建将不可改变 t3 = ('a',) # 元组只有一个元素,一定要加逗号',' t4 = (['a','b','c']) # 空列表方式2
Note: tuple if there is only one element of an object, must be a comma behind
,
or become other types of data. -
Index
with lists, not too much, for example.t = ('a','b','c','d') print(t[0]) print(t[-1]) # 输出结果如下: a d
-
Inquire
With lists, not too much, for example.
t = ('a','b','c','d') print(t.index('a')) print(t.count('a')) print(len(t)) # 输出结果如下: 0 1 4
-
CRUD
It is the tuple
不可变
type, not CRUD element object.But pay attention to the following scene:
Element object (memory address) tuples immutable, mutable type. ---- Here reference type of situation has emerged.
# 元组的元组不可修改(即内存地址) t = ([1],) t[0]= 100 print(t) # 结果报错了 TypeError: 'tuple' object does not support item assignment ############################################ # 元组里面的引用类型对象可以修改(如嵌套了列表) t = ([1],2,3) t[0][0] = 100 # 对元组引用类型对象的元素作修改 print(t) # 输出结果如下: ([100], 2, 3)
2.2.3 string string
Description: The character string is composed of several characters, and a 有序不可变
data structure, the use of quotation marks.
-
Initializing
a variety of patterns, single and double quotation marks, three marks and the like.name = 'tom' age = 18 str1 = 'abc' # 单引号字符串 str2 = "abc" # 双引号字符串 str3 = """I'm python""" # 三引号字符串 str4 = r"c:\windows\note" # r前缀,没有转义(转义字符不生效) str5 = f'{name} is {age} age.' # f前缀,字符串格式化,v3.6支持 print(type(str1), str1) print(type(str2), str2) print(type(str3), str3) print(type(str4), str4) print(type(str5), str5) # 输出结果如下: <class 'str'> abc <class 'str'> abc <class 'str'> I'm python <class 'str'> c:\windows\note <class 'str'> tom is 18 age.
-
index
With lists, not too much, for example.
str = "abcdefg" print(str[0]) print(str[-1]) # 输出结果如下: a g
-
connection
The plus sign
+
plurality of strings together and returns a new string.str1 = "abcd" str2 = "efg" print(str1 + str2) # 输出结果如下: abcdefg
join () method:
S.join(iterable) -> str
s represents delimiter string, as Iterable iterables string , return a result string.
str = "abcdefg" print('->'.join(str)) # 输出结果如下: a->b->c->d->e->f->g
-
Find character
find () method:
S.find(sub[, start[, end]]) -> int
From left to right to find substring sub, you can also specify the interval, find returns a positive index, returns can not be found
-1
.str = "abcdefg" print(str.find('a',0,7)) print(str.find('A')) # 输出结果如下: 0 -1
rfind () Method:
S.rfind(sub[, start[, end]]) -> int
From right to left to find substring sub, you can also specify the interval, find returns a positive index, returns can not be found
-1
.str = "abcdefg" print(str.rfind('a')) print(str.rfind('A')) # 输出结果如下: 0 -1
There
index()
andfind()
similar, but can not find the will throw an exception, not recommended.Like
s.count()
you can also count the number of characters appear.Like
len(s)
you can also count the length of the string. -
Split
split () method:
S.split(sep=None, maxsplit=-1) -> list of strings
represents sep separator, the default is an empty string, maxsplit = -1 indicates traverse the entire string, and returns the list.
str = "a,b,c,d,e,f,g" print(str.split(sep=',')) # 输出结果如下: ['a', 'b', 'c', 'd', 'e', 'f', 'g']
rsplit () method is different from above, from right to left traversal.
The splitlines () Method:
S.splitlines([keepends]) -> list of strings
Press OK to cut the string, keepends indicating whether the reserved line separator, and finally return to the list.
str = "a\nb\nc\r\nd" print(str.splitlines()) print(str.splitlines(keepends=True)) # 输出结果如下: ['a', 'b', 'c', 'd'] ['a\n', 'b\n', 'c\r\n', 'd']
Partition () Method :
S.partition(sep) -> (head, sep, tail)
From left to right delimiter query, it is divided into a first face, a separator, triplet tail, returns a tuple tuple.
str = "a*b*c*d" print(str.partition('*')) # 输出结果如下: ('a', '*', 'b*c*d')
rpartition () Method :
S.rpartition(sep) -> (head, sep, tail)
Unlike the way, it is from right to left, but the more commonly used, you can get some of the information suffix.
str1 = "http://www.python.org:8843" str2 = str1.rpartition(':') port = str2[-1] print(port)
-
replace
replace () method:
S.replace(old, new[, count]) -> str
Traverse the entire string to find the Replace All, count represents the number of replacement, the default Replace All, and finally a return
新的字符串
.str = "www.python.org" print(str.replace('w','m')) # 返回的是一个新的字符串 print(str) # 字符串不可变,保持原样 # 输出结果如下: mmm.python.org www.python.org
-
Remove
strip () Method:
S.strip([chars]) -> str
Removes the specified string at both ends
字符集chars
, remove the default blank characters.str = " * www.python.org *" print(str.strip("* ")) # 去掉字符串首尾带有星号'*' 和 空白' ' # 输出结果如下: www.python.org
There
lstrip()
andrstrip
are removing the string left and right character set. -
Analyzing inclusive
startsWith () Method:
S.startswith(prefix[, start[, end]]) -> bool
Default determine whether there is the beginning of the string specified character prefix, you can also be specified interval.
str = "www.python.org" print(str.startswith('www',0,14)) print(str.startswith('p',0,14)) # 输出结果如下: True False
endsWith () Method:
S.endswith(suffix[, start[, end]]) -> bool
The default is determined whether the end of the specified character string with a suffix, can also be specified interval.
str = "www.python.org" print(str.startswith('www',0,14)) print(str.startswith('p',0,14)) # 输出结果如下: True False
str = "www.python.org" print(str.endswith('g',11,14)) # 输出结果如下: True
-
format
c style format:
Format string: using% s (corresponding to a string value),% d (corresponding to a digital value) and the like, may also be inserted in the middle modifiers% 03d.
The value of the format: an object only, or may be a tuple dictionary.
name = "Tom" age = 18 print("%s is %d age." % (name,age)) # 输出结果如下: Tom is 18 age.
format Format:
Format string: using braces {}, which braces modifiers can be used.
The value of the format: * args variable position parameters, ** kwargs keyword is a variable parameter.
# 位置传参 print("IP={} PORT={}".format('8.8.8.8',53)) # 位置传参 print("{Server}: IP={1} PORT={0}".format(53, '8.8.8.8', Server='DNS Server')) # 位置和关键字传参传参 # 输出结果如下: IP=8.8.8.8 PORT=53 DNS Server: IP=8.8.8.8 PORT=53
# 浮点数 print("{}".format(0.123456789)) print("{:f}".format(0.123456789)) # 小数点默认为6位 print("{:.2f}".format(0.123456789)) # 取小数点后两位 print("{:15}".format(0.123456789)) # 宽度为15,右对齐 # 输出结果如下: 0.123456789 0.123457 # 为什么是这个值?大于5要进位 0.12 0.123456789 # 左边有4个空格
-
Other commonly used functions
str = "DianDiJiShu" print(str.upper()) # 字母全部转化为大写 print(str.lower()) # 字母全部转化为小写 # 输出结果如下: DIANDIJISHU diandijishu
2.2.4 bytes bytes
bytes
And bytearray
two data types introduced from python3.
In the computer world, it is a machine 0
and 1
composition, also known as binary (bytes) to communicate, we call this coding ASCII
coding.
So the machine language of communication is called machine language. However, we humans want to communicate with the machine, you need to how to do it?
- Encoding the human language into a machine-readable language, usually called encoded (converted to ASCII code strings).
- Decoding the machine language human-readable language, often called decoding (ASCII code converted to a string).
So far the modern history of the encoding process is probably this: ASCII (1 byte) -> unicode (2 ~ 4 bytes) -> utf8 (1 6 bytes), utf8 is multi-byte encoding, general use 1 3 bytes, 4 bytes of particular use (typically 3 bytes using Chinese), backward compatible with ASCII encoding.
China also has its own coding: gbk
ASCII code table used must be kept in mind (finishing section):
Details ASCII code download link:
链接:https://pan.baidu.com/s/1fWVl57Kqmv-tkjrDKwPvSw 提取码:tuyz
Therefore, the machine is hexadecimal bytes, 1 byte is equal to 8, for example: decimal 2, in binary and hexadecimal:
# 二进制
0000 0010 # 一个字节bytes
# 16进制,机器基本都是显示16进制
0x2
bytes is immutable
bytes() # 空bytes,一旦创建不可改变
bytes(int) # 指定字节的大小,用0填充
bytes(iterable_of_ints) # [0.255]整数的可迭代对象
bytes(string, encoding[, errors]) # 等价于string.encoding(),字符串编码成字节
bytes(bytes_or_buffer) # 复制一份新的字节对象
-
initialization
b1 = bytes() b2 = bytes(range(97,100)) b3 = bytes(b2) b4 = bytes('123',encoding='utf-8') b5 = b'ABC' b6 = b'\xe4\xbd\xa0\xe5\xa5\xbd'.decode('utf-8') print(b1, b2, b3, b4, b5, b6, sep='\n') # 输出结果如下: b'' b'abc' b'abc' b'123' b'ABC' 你好
2.2.5 bytearray byte array
bytearray variable array, additions and deletions may operate similar list.
bytearray() # 空bytearray,可改变
bytearray(iterable_of_ints) # [0.255]整数的可迭代对象
bytearray(string, encoding[, errors]) # 等价于string.encoding(),字符串编码成字节
bytearray(bytes_or_buffer) # 复制一份新的字节数组对象
bytearray(int) # 指定字节的大小,用0填充
-
CRUD
# 初始化 b = bytearray() print(b) # 输出结果如下: bytearray(b'') #-------------------------- # 增加元素对象 b.append(97) print(b) b.extend([98,99]) print(b) # 输出结果如下: bytearray(b'a') bytearray(b'abc') #-------------------------- # 插入元素对象 b.insert(0,65) print(b) # 输出结果如下: bytearray(b'Aabc') #-------------------------- # 删除元素对象 b.pop() print(b) # 输出结果如下: bytearray(b'Aab')
We went to this today, and we then followed the next round Laoke set (集合)
and dict (字典)
appreciate your patience.
If you like my articles, I welcome the attention of the public number: drip technique, scan code concerned, from time to time to share