Common data structures in Python can be collectively referred to as containers. There are three main types of containers: sequence (list, tuple and string), mapping (such as dictionary) and set.
1. Sequence
The sequence is ordered, and each element in the sequence has its own number. Python has 6 built-in sequences, including lists, tuples, strings, Unicode strings, buffer objects, and xrange objects.
1.1 string
1.1.1 create string
a = 'hello world' print(type(a)) # <class 'str'> name1 = 'Tom' # The three quotation mark string supports line feed b = ''' i am Tom, nice to meet you! ''' c = "I'm Tom" d = 'I\'m Tom'
1.1.2 string input and output
# output print('hello world') name = 'Tom' print('My name is%s' % name) print(f'My name is{name}') # input name = input('Please enter your name:') print(f'The name you entered is{name}') print(type(name))
1.1.3 subscript
Subscript, also known as index, is the number, starting from 0.
name = "abcdef" print(name[1]) print(name[0]) print(name[2])
1.1.4 slicing
Slicing refers to the operation of intercepting part of the operated object. String, list and tuple all support slicing operation.
sequence[Start position subscript:End position subscript:step]
be careful
- Excluding the data corresponding to the end position subscript, positive and negative integers can be used;
- The step size is the selection interval, which can be positive or negative integers. The default step size is 1.
name = "abcdefg" print(name[2:5:1]) # cde print(name[2:5]) # cde print(name[:5]) # abcde print(name[1:]) # bcdefg print(name[:]) # abcdefg print(name[::2]) # aceg print(name[:-1]) # abcdef, negative 1 indicates the penultimate data print(name[-4:-1]) # def print(name[::-1]) # gfedcba
1.1.5 common operation methods
1.1.5.1 search
The so-called string search method is to find the position or number of occurrences of the substring in the string.
- find()
Check whether a substring is included in the string. If the subscript is at the beginning of the substring, otherwise - 1 will be returned.
String sequence.find(Substring, Start position subscript, End position subscript)
Note: the start and end subscripts can be omitted, indicating that they are found in the whole string sequence.
mystr = "hello world and itcast and itheima and Python" print(mystr.find('and')) # 12 print(mystr.find('and', 15, 30)) # 23 print(mystr.find('ands')) # -1
- index()
Detect whether a substring is included in this string. If the subscript is returned at the beginning of this substring, otherwise an exception will be reported.
String sequence.index(Substring, Start position subscript, End position subscript)
Note: the start and end subscripts can be omitted, indicating that they are found in the whole string sequence.
mystr = "hello world and itcast and itheima and Python" print(mystr.index('and')) # 12 print(mystr.index('and', 15, 30)) # 23 print(mystr.index('ands')) # report errors
- rfind()
It has the same function as find(), but the search direction starts from the right. - rindex()
- It has the same function as index(), but the search direction starts from the right.
- count()
Returns the number of occurrences of a substring in a string
String sequence.count(Substring, Start position subscript, End position subscript)
Note: the start and end subscripts can be omitted, indicating that they are found in the whole string sequence.
mystr = "hello world and itcast and itheima and Python" print(mystr.count('and')) # 3 print(mystr.count('ands')) # 0 print(mystr.count('and', 0, 20)) # 1
1.1.5.2 modification
Modifying a string means modifying the data in the string in the form of a function.
- replace(): replace
String sequence.replace(Old substring, New substring, Replacement times)
Note: if the replacement times exceed the occurrence times of the substring, the replacement times are the occurrence times of the substring.
mystr = "hello world and itcast and itheima and Python" # Result: hello world he itcast he itheima he Python print(mystr.replace('and', 'he')) # Result: hello world he itcast he itheima he Python print(mystr.replace('and', 'he', 10)) # Result: hello world and itcast and itheima and Python print(mystr)
Note: data can be divided into variable type and immutable type according to whether it can be modified directly. When modifying the data of string type, the original string cannot be changed. It belongs to the type that cannot modify the data directly, that is, the immutable type.
- split()
Splits the string according to the specified character.
String sequence.split(Split character, num)
Note: num indicates the number of split characters. The number of data to be returned is num+1.
mystr = "hello world and itcast and itheima and Python" # Result: ['hello world', 'itcast', 'itheima', 'Python'] print(mystr.split('and')) # Result: ['hello world', 'itcast', 'itheima and Python'] print(mystr.split('and', 2)) # Results: ['hello', 'world', 'and', 'itcast', 'and', 'itheima', 'and', 'Python'] print(mystr.split(' ')) # Results: ['Hello ',' world ',' itcast and itheima and Python '] print(mystr.split(' ', 2))
- join()
Combining strings with one character or substring is to combine multiple strings into a new string.
Character or substring.join(A sequence of multiple strings)
list1 = ['chuan', 'zhi', 'bo', 'ke'] t1 = ('aa', 'b', 'cc', 'ddd') # Result: chuan_zhi_bo_ke print('_'.join(list1)) # Result: AA b... cc... ddd print('...'.join(t1))
- capitalize()
Converts the first character of a string to uppercase.
mystr = "hello world and itcast and itheima and Python" # Result: Hello world and itcast and itheima and python print(mystr.capitalize())
Note: after the capitalization() function is converted, only the first character of the string is capitalized, and all other characters are lowercase.
- title()
Converts the first letter of each word in a string to uppercase.
mystr = "hello world and itcast and itheima and Python" # Result: Hello World And Itcast And Itheima And Python print(mystr.title())
- lower()
Converts uppercase to lowercase in a string.
mystr = "hello world and itcast and itheima and Python" # Result: hello world and itcast and itheima and python print(mystr.lower())
- upper()
Converts the small case of a string to uppercase.
mystr = "hello world and itcast and itheima and Python" # Result: HELLO WORLD AND ITCAST AND ITHEIMA AND PYTHON print(mystr.upper())
- lstrip()
Delete the white space character to the left of the string.
mystr = " hello world and itcast and itheima and Python " # hello world and itcast and itheima and Python print(mystr.lstrip()) # hello world and itcast and itheima and Python print(mystr.rstrip()) # hello world and itcast and itheima and Python print(mystr.strip())
- rstrip() removes the white space character to the right of the string.
- strip() deletes white space characters on both sides of the string
.
- ljust()
Returns a left justified original string and fills it with a new string of the corresponding length using the specified character (default space).
String sequence.ljust(length, Fill character)
mystr2='hello' mystr2.ljust(10,'.') # 'hello.....' mystr2.ljust(10) # 'hello ' mystr2.rjust(10,'.') # '.....hello' mystr2.center(10,'.') # '..hello...'
- rjust() returns a right aligned original string and fills it with a new string of corresponding length with the specified character (default space). The syntax is the same as ljust().
- center() returns a new string centered on the original string and filled with the specified character (default space) to the corresponding length. The syntax is the same as ljust().
1.1.5.3 judgment
The so-called judgment is to judge whether it is True or False. The returned result is Boolean data type: True or False.
- startswith()
Check whether the string starts with the specified substring. If yes, it returns True; otherwise, it returns False. If the start and end position subscripts are set, check within the specified range.
String sequence.startswith(Substring, Start position subscript, End position subscript)
mystr = "hello world and itcast and itheima and Python " # Result: True print(mystr.startswith('hello')) # Result False print(mystr.startswith('hello', 5, 20))
- endswith()
Check whether the string ends with the specified substring. If yes, it returns True; otherwise, it returns False. If the start and end position subscripts are set, check within the specified range.
String sequence.endswith(Substring, Start position subscript, End position subscript)
mystr = "hello world and itcast and itheima and Python" # Result: True print(mystr.endswith('Python')) # Result: False print(mystr.endswith('python')) # Result: False print(mystr.endswith('Python', 2, 20))
- isalpha()
Returns True if the string has at least one character and all characters are letters, otherwise returns False.
mystr1 = 'hello' mystr2 = 'hello12345' # Result: True print(mystr1.isalpha()) # Result: False print(mystr2.isalpha())
- isdigit()
Returns True if the string contains only numbers; otherwise, returns False.
mystr1 = 'aaa12345' mystr2 = '12345' # Result: False print(mystr1.isdigit()) # Result: False print(mystr2.isdigit())
- isalnum()
Returns True if the string has at least one character and all characters are letters or numbers, otherwise returns False.
mystr1 = 'aaa12345' mystr2 = '12345-' # Result: True print(mystr1.isalnum()) # Result: False print(mystr2.isalnum())
- isspace()
Returns True if the string contains only white space; otherwise, returns False.
mystr1 = '1 2 3 4 5' mystr2 = ' ' # Result: False print(mystr1.isspace()) # Result: True print(mystr2.isspace())
1.2 tuples
Tuple characteristics:
- Use parentheses () and separate the data with commas;
- Data can be different data types;
- A tuple can store multiple data, and the data in the tuple cannot be modified (immutable type)
1.2.1 creating tuples
# Multiple data tuples t1 = (10, 20, 30) # Single data tuple t2 = (10,)
Note: if the defined tuple has only one data, add a comma after the data, otherwise the data type is the only data type of the data
t2 = (10,) print(type(t2)) # tuple t3 = (20) print(type(t3)) # int t4 = ('hello') print(type(t4)) # str
1.2.2 common operations
Tuple data does not support modification, only search.
- Find data by subscript
tuple1 = ('aa', 'bb', 'cc', 'bb') print(tuple1[0]) # aa
- index()
Find a data. If the data exists, return the corresponding subscript. Otherwise, an error is reported. The syntax is the same as the index method of list and string.
tuple1 = ('aa', 'bb', 'cc', 'bb') print(tuple1.index('aa')) # 0
- count()
Count the number of times a data appears in the current tuple.
tuple1 = ('aa', 'bb', 'cc', 'bb') print(tuple1.count('bb')) # 2
- len()
Count the number of data in tuples.
tuple1 = ('aa', 'bb', 'cc', 'bb') print(len(tuple1)) # 4
- Modify variable type elements in tuples
If the direct data in the tuple is modified, an error will be reported immediately. However, if there is a list in the tuple, modifying the data in the list is supported, so self-awareness is very important.
tuple1 = ('aa', 'bb', 'cc', 'bb') tuple1[0] = 'aaa' # report errors tuple2 = (10, 20, ['aa', 'bb', 'cc'], 50, 30) print(tuple2[2]) # Access to list # Results: (10, 20, ['aaaaa ',' BB ',' CC '], 50, 30) tuple2[2][0] = 'aaaaa' print(tuple2)
1.3 list
1.3.1 create list
# [data 1, data 2, data 3, data 4...] lst1=[1,2,3] lst2=list() # []
1.3.2 common operations of list
Add, delete, modify and check.
1.3.2.1 search
subscript
name_list = ['Tom', 'Lily', 'Rose'] print(name_list[0]) # Tom print(name_list[1]) # Lily print(name_list[2]) # Rose
function
- index()
List sequence.index(data, Start position subscript, End position subscript)
name_list = ['Tom', 'Lily', 'Rose'] print(name_list.index('Lily', 0, 2)) # 1
- count()
Counts the number of times the specified data appears in the current list.
name_list = ['Tom', 'Lily', 'Rose'] print(name_list.count('Lily')) # 1
- len()
Access list length, that is, the number of data in the list.
name_list = ['Tom', 'Lily', 'Rose'] print(len(name_list)) # 3
Judge whether it exists
In: judge whether the specified data is in a list sequence. If yes, return True; otherwise, return False
Not in: judge whether the specified data is not in a list sequence. If not, return True; otherwise, return False
name_list = ['Tom', 'Lily', 'Rose'] # Result: True print('Lily' in name_list) # Result: False print('Lilys' in name_list) # Result: False print('Lily' not in name_list) # Result: True print('Lilys' not in name_list)
1.3.2.2 add
- append()
Append data to the end of the list.
List sequence.append(data)
When adding data to the list, the specified data is directly added to the original list, that is, the original list is modified, so the list is variable type data.
name_list = ['Tom', 'Lily', 'Rose'] name_list.append('xiaoming') # Results: ['Tom', 'Lily', 'Rose', 'xiaoming'] print(name_list)
If the data appended by append() is a sequence, the whole sequence is appended to the list
- extend()
Add data at the end of the list. If the data is a sequence, add the data of this sequence to the list one by one.
List sequence.extend(data)
name_list = ['Tom', 'Lily', 'Rose'] name_list.extend('xiaoming') # Results: ['Tom', 'Lily', 'Rose', 'x', 'I', 'a', 'o','m ',' I ',' n ',' g '] print(name_list) name_list = ['Tom', 'Lily', 'Rose'] name_list.extend(['xiaoming', 'xiaohong']) # Results: ['Tom', 'Lily', 'Rose', 'xiaoming', 'xiaohong'] print(name_list)
- insert()
Add data at the specified location.
List sequence.insert(Position subscript, data)
name_list = ['Tom', 'Lily', 'Rose'] name_list.insert(1, 'xiaoming') # Results: ['Tom', 'xiaoming', 'Lily', 'Rose'] print(name_list)
1.3.2.3 delete
- del()
del target
Delete list
name_list = ['Tom', 'Lily', 'Rose']
Delete specified data
name_list = ['Tom', 'Lily', 'Rose'] del name_list[0] # Result: ['lily ',' Rose '] print(name_list)
- pop()
Delete the data of the specified subscript (the last one by default) and return the data.
List sequence.pop(subscript)
name_list = ['Tom', 'Lily', 'Rose'] del_name = name_list.pop(1) # Result: Lily print(del_name) # Result: [Tom ',' Rose '] print(name_list)
- remove()
Remove the first match of a data in the list.
List sequence.remove(data)
name_list = ['Tom', 'Lily', 'Rose'] name_list.remove('Rose') # Result: [Tom ',' Lily '] print(name_list)
- clear()
clear list
name_list = ['Tom', 'Lily', 'Rose'] name_list.clear() print(name_list) # Result: []
1.3.2.4 modification
- Modify specified subscript data
name_list = ['Tom', 'Lily', 'Rose'] name_list[0] = 'aaa' # Result: ['aaa ',' Lily ',' Rose '] print(name_list)
- reverse(): reverse
num_list = [1, 5, 2, 3, 6, 8] num_list.reverse() # Result: [8, 6, 3, 2, 5, 1] print(num_list)
- sort() sort
Sequence list.sort( key=None, reverse=False)
num_list = [1, 5, 2, 3, 6, 8] num_list.sort() # Results: [1, 2, 3, 5, 6, 8] print(num_list)
1.3.2.5 copying
- copy()
name_list = ['Tom', 'Lily', 'Rose'] name_li2 = name_list.copy() # Result: ['Tom', 'Lily', 'Rose'] print(name_li2)
1.3.3 list loop traversal
# while name_list = ['Tom', 'Lily', 'Rose'] i = 0 while i < len(name_list): print(name_list[i]) i += 1 # for name_list = ['Tom', 'Lily', 'Rose'] for i in name_list: print(i)
1.3.4 list nesting
name_list = [['Xiao Ming', 'Xiao Hong', 'Little green'], ['Tom', 'Lily', 'Rose'], ['Zhang San', 'Li Si', 'Wang Wu']] # Step 1: click the subscript to find the list where Li Si is located print(name_list[2]) # Step 2: from the list where Li Si is located, click the subscript to find the data Li Si print(name_list[2][1])
2. Mapping
2.1 dictionary
2.1.1 create dictionary
Dictionary features:
- The symbol is braces
- The data appears in the form of key value pairs
- Key value pairs are separated by commas
# There is a data dictionary dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'} # Empty dictionary dict2 = {} dict3 = dict()
Take the element in seq sequence as the key of the dictionary, and value is the initial value corresponding to all keys of the dictionary
dict.fromkeys(seq[, value])
- seq – dictionary key value list.
- Value – optional parameter to set the value of key sequence (seq).
seq = ('Google', 'Runoob', 'Taobao') thisdict = dict.fromkeys(seq) print "The new dictionary is : %s" % str(dict) # The new dictionary is: {Google ': none,' Taobao ': none,' runoob ': none} thisdict = dict.fromkeys(seq, 10) print "The new dictionary is : %s" % str(thisdict) # The new dictionary is: {Google ': 10,' Taobao ': 10,' runoob ': 10}
2.1.2 common operations of dictionary
Add, delete, modify and query
2.1.2.1 add
Dictionary sequence[key] = value
Note: if the key exists, modify the value corresponding to the key; If the key does not exist, add this key value pair.
dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'} dict1['name'] = 'Rose' # Results: {name ':' Rose ',' age ': 20,' gender ':' male '} print(dict1) dict1['id'] = 110 # {'name': 'Rose', 'age': 20, 'gender': 'male', 'id': 110} print(dict1)
2.1.2.2 delete
- del() /del
Delete the dictionary or delete the specified key value pair in the dictionary
dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'} del dict1['gender'] # Result: {name ':'Tom','age ': 20} print(dict1)
- clear
Empty dictionary
dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'} dict1.clear() print(dict1) # {}
2.1.2.3 modification
- Modify according to key
Dictionary sequence[key] = value
Note: if the key exists, modify the value corresponding to the key; If the key does not exist, add this key value pair.
- update()
Update the key / value pair of dictionary dict2 into dict.
dict.update(dict2)
tinydict = {'Name': 'Zara', 'Age': 7} tinydict2 = {'Sex': 'female' } tinydict.update(tinydict2) print ("Value : %s" % tinydict) # Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'}
2.1.2.4 check
- key value search
dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'} print(dict1['name']) # Tom print(dict1['id']) # report errors
If the key currently searched exists, the corresponding value will be returned; Otherwise, an error will be reported.
- get()
Dictionary sequence.get(key, Default value)
Note: if the key currently searched does not exist, the second parameter (default value) is returned. If the second parameter is omitted, None is returned.
dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'} print(dict1.get('name')) # Tom print(dict1.get('id', 110)) # 110 print(dict1.get('id')) # None
- keys()
dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'} print(dict1.keys()) # dict_keys(['name', 'age', 'gender'])
- values()
dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'} print(dict1.values()) # dict_values(['Tom', 20, 'male'])
- items()
dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'} print(dict1.items()) # dict_ Items ([('name ',' Tom '), ('age', 20), ('gender ',' male '))
2.1.3 dictionary loop traversal
dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'} # Traversal key for key in dict1.keys(): print(key) # Traversal value for value in dict1.values(): print(value) # Traversal element for item in dict1.items(): print(item) # Traverse key value pairs for key, value in dict1.items(): print(f'{key} = {value}')
3. Set
Collection features:
- Set can remove duplicate data;
- The set data is out of order, so subscripts are not supported
3.1 creating collections
Create a collection using {} or set(), but if you want to create an empty collection, you can only use set(), because {} is used to create an empty dictionary.
s1 = {10, 20, 30, 40, 50} print(s1) s2 = {10, 30, 20, 10, 30, 40, 30, 50} print(s2) s3 = set('abcdefg') print(s3) s4 = set() print(type(s4)) # set s5 = {} print(type(s5)) # dict
3.2 common operation methods of collection
3.2.1 add
- add()
s1 = {10, 20} s1.add(100) s1.add(10) print(s1) # {100, 10, 20}
Because the set has the function of de duplication, when the data added to the set is the existing data of the current set, no operation will be carried out.
- update()
The additional data is a sequence.
s1 = {10, 20} # s1.update(100) # report errors s1.update([100, 200]) s1.update('abc') print(s1)
3.2.2 delete
- remove()
Delete the specified data in the collection. If the data does not exist, an error will be reported
s1 = {10, 20} s1.remove(10) print(s1) s1.remove(10) # report errors print(s1)
- discard()
Delete the specified data in the collection. If the data does not exist, no error will be reported.
s1 = {10, 20} s1.discard(10) print(s1) s1.discard(10) print(s1)
- pop()
Randomly delete a data in the set and return this data.
s1 = {10, 20, 30, 40, 50} del_num = s1.pop() print(del_num) print(s1)
3.2.1 check
- In determines whether the data is in the set sequence
- not in judge whether the data is in the set sequence
s1 = {10, 20, 30, 40, 50} print(10 in s1) # True print(10 not in s1) # False
4. Public operation
4.1 operators
operator | describe | Supported container types |
---|---|---|
+ | merge | String, list, tuple |
* | copy | String, list, tuple |
in | Does the element exist | String, list, tuple, dictionary |
not in | Does the element not exist | String, list, tuple, dictionary |
# + # 1. String str1 = 'aa' str2 = 'bb' str3 = str1 + str2 print(str3) # aabb # 2. List list1 = [1, 2] list2 = [10, 20] list3 = list1 + list2 print(list3) # [1, 2, 10, 20] # 3. Tuple t1 = (1, 2) t2 = (10, 20) t3 = t1 + t2 print(t3) # (10, 20, 100, 200) # * # 1. String print('-' * 10) # ---------- # 2. List list1 = ['hello'] print(list1 * 4) # ['hello', 'hello', 'hello', 'hello'] # 3. Tuple t1 = ('world',) print(t1 * 4) # ('world', 'world', 'world', 'world') # in or not in # 1. String print('a' in 'abcd') # True print('a' not in 'abcd') # False # 2. List list1 = ['a', 'b', 'c', 'd'] print('a' in list1) # True print('a' not in list1) # False # 3. Tuple t1 = ('a', 'b', 'c', 'd') print('aa' in t1) # False print('aa' not in t1) # True
4.2 public methods
function | describe |
---|---|
len() | Calculate the number of elements in the container |
Del or del() | delete |
max() | Returns the maximum value of the element in the container |
min() | Returns the minimum value of the element in the container |
range(start, end, step) | Generate a number from start to end in step for the for loop |
enumerate() | Function is used to combine a traversable data object (such as list, tuple or string) into an index sequence, and list data and data subscripts at the same time. It is generally used in the for loop. |
- len()
# 1. String str1 = 'abcdefg' print(len(str1)) # 7 # 2. List list1 = [10, 20, 30, 40] print(len(list1)) # 4 # 3. Tuple t1 = (10, 20, 30, 40, 50) print(len(t1)) # 5 # 4. Assemble s1 = {10, 20, 30} print(len(s1)) # 3 # 5. Dictionary dict1 = {'name': 'Rose', 'age': 18} print(len(dict1)) # 2
- del()
# 1. String str1 = 'abcdefg' del str1 print(str1) # 2. List list1 = [10, 20, 30, 40] del(list1[0]) print(list1) # [20, 30, 40]
- max() min()
# 1. String str1 = 'abcdefg' print(min(str1)) # a print(max(str1)) # g # 2. List list1 = [10, 20, 30, 40] print(min(list1)) # 10 print(max(list1)) # 40
- range()
# 1 2 3 4 5 6 7 8 9 for i in range(1, 10, 1): print(i) # 1 3 5 7 9 for i in range(1, 10, 2): print(i) # 0 1 2 3 4 5 6 7 8 9 for i in range(10): print(i)
Note: the sequence generated by range() does not contain the end number.
- enumerate()
enumerate(Traversable object, start=0)
Note: the start parameter is used to set the starting value of the subscript of traversal data, which is 0 by default.
list1 = ['a', 'b', 'c', 'd', 'e'] for i in enumerate(list1): print(i) for index, char in enumerate(list1, start=1): print(f'The subscript is{index}, The corresponding character is{char}')
4.3 container type conversion
- tuple()
Convert a sequence into tuples
list1 = [10, 20, 30, 40, 50, 20] s1 = {100, 200, 300, 400, 500} print(tuple(list1)) print(tuple(s1))
- list()
Convert a sequence into a list.
t1 = ('a', 'b', 'c', 'd', 'e') s1 = {100, 200, 300, 400, 500} print(list(t1)) print(list(s1))
- set()
Convert a sequence into a set.
list1 = [10, 20, 30, 40, 50, 20] t1 = ('a', 'b', 'c', 'd', 'e') print(set(list1)) print(set(t1))