Summary of the second week
1. Installation environment
-
Download requests pip package
Modify the download source of the third-party library to the domestic mirror website ---> pip config set global.index-url https://pypi.doubanio.com/simple Third party Library ---> requests ---> pip install requests agreement ---> The rules of conversation to be observed by both sides of communication. HTTP / HTTPS ---> adopt URL Protocol for accessing network resources ---> Hyper-Text Transfer Protocol(Hypertext Transfer Protocol) Request( request) - Respond( response)
2. Knowledge summary
1. List
-
1. Three ways to build lists
list1=['a','b','c'] # Method 1 of creating list: literal syntax list2=list(range(1,10)) # Create list method 2: constructor method list3=[i** 2for i in range(1,10)] # Create list method 3, generative (deductive) syntax
-
2. List function, traversal index, member operation, merging, ratio size (according to the first number, letter, Chinese character, according to Kangxi dictionary)
for i ,x in enumerate(list1): print(i,x) # Traversal, you can add labels print(10 in list3) print(5 not in list2) # Member operation list5=[1,3,5,7] list6=[4,4,8] list6+=list5 print(list6) # merge list7= list(range(1,8,2)) list8=[0,3,5,7,9] print(list7>list8) # Than the size than the first number list9 =['apply'] list10 =['black'] print(list9>list10) # According to the coding ratio of letters print('Da Chui Wang'<'You Duanwei') # Kangxi dictionary
-
3. List operation, add (two), delete (three), find the display position, calculate the number, reverse the list, and sort the list. If
The elements in the list are in string form and can be converted to integersnums =[0,10,100,1000] nums.append(10000) # Add a data at the end nums.insert(1,5) # Adds an element at the specified location nums.pop() # Delete the last element nums.pop(0) # Deletes the element at the specified location del nums[0] # Delete the element at the specified location, which is not commonly used nums.remove(1000) # If there are more than 1000 Remove first while 1000 in nums: nums.remove(1000) # Delete all 1000 if 1000 in nums: print(nums.index(1000)) # Displays the location of 1000 if 1000 in nums: print(nums.count(1000)) # Count 1000 nums.reverse() # Reverse operation nums.sort() # Sorting: ascending by default, from small to large. (reverse=True) can be changed to descending order. nums.sort(key=int) # Convert the elements of the list to integer sort
-
4. Sampling in the list, 3 kinds of sampling and 1 kind of disorder
import random nums =[1,2,3,4,5,6,7,8,9,10] print(random.sample(nums,k=5)) # Sampling without return print(random.choices(nums,k=5)) # Yes, put it back for sampling print(random.choice(nums)) # Select one at random random.shuffle(nums) print(nums) # Reorder
2. Tuple
-
1. Repeat operation, member operation, merge operation, index slice (tuple is an immutable container, which is the same as list except that it cannot be changed)
a=(0,) b=(1,2,4) # Tuples are immutable containers print(type(a)) print(a*3) # Repeat operation print(3 in b) print(2 not in b) # Member operation c=a+b print(c) # Merge operation print(a[0],b[1:3]) # Index slice # However, it cannot be modified (added or deleted)
3. String
-
1. There are three ways to build strings
a='hello' b ="hello" c=""" hello """ print(a,b,c) # There are three ways to enter a string
-
2. String tab, line break, placeholder, escape
s1 = '\time up \now' print(s1) # In string s1, \ tis a tab character (four spaces), \ NIS a newline character s2 = r'\time up \now' print(s2) # String with placeholder, keep the original meaning s3 = '\141\142\143\x61\x62\x63' print(s3) s4 ='\u9a86 \u660a' print(s4) # \u. Escape to Chinese
-
3. For string operation, note: string is also a constant data type, and can only be read, not rewritten!!! Gets the length of the string (the string has no subscript, which is the same as the collection). Loop traversal, repetition, member operation, comparison size (character encoding size), string splicing.
a = 'hello, world' # Gets the length of the string print(len(a)) # TypeError: 'str' object does not support item assignment # a[0] = 'H' # Loop through each character of the string for i in range(len(a)): print(a[i]) for i in a: print(i) # repeat print(a * 5) # Member operation print('or' in a) print('ko' in a) b = 'hello, World' # Comparison operation (compare the contents of string -- > character encoding size) print(a == b) print(a != b) c = 'goodbye, world' print(b > c) d = 'hello, everybody' print(b >= d) print(ord('W'), ord('e')) # String splicing e = '!!!' print(d + e) f = ' goodbye' print(d + e + f)
-
4. String transformation, four kinds of conversion to case, four kinds of judgment, head and tail judgment
a = 'i LOVE you' # Capitalize print(a.upper()) # Turn lowercase print(a.lower()) # title case print(a.capitalize()) # Capitalize each word print(a.title()) b = 'abc123' # Determine whether the string is a number print(b.isdigit()) # Determine whether the string is a letter print(b.isalpha()) # Determine whether the string is a letter or a number print(b.isalnum()) # Determine whether the string is an ASCII character # A method added in Python 3.7 print(b.isascii()) c = 'How do you do' print(c.isascii()) # Determines whether the string starts with the specified content print(c.startswith('Hello')) # Determines whether the string ends with the specified content print(c.endswith('ah'))
-
5. Find the word position specified in the string (two types)
a = 'Oh apple, i love apple.' # index - find the specified substring from left to right. You can specify where to start. The default is 0 # The index (subscript) corresponding to the returned substring is found, and a direct error is reported if it is not found (program crash) print(a.index('apple')) print(a.index('apple', 10)) print(a.rindex('apple')) # ValueError: substring not found # print(a.index('banana')) print(a.find('apple')) print(a.find('apple', 10)) print(a.rfind('apple')) print(a.find('banana')) print(a.rfind('banana'))
-
6. String, right justified, left justified
print(a.center(30,' ')) # The center method centers the string with a width of 80 print(a.rjust(60,'*')) # The rjust method aligns the string to the right with a width of 60 print(a.ljust(20,'-')) # The ljust method aligns the string to the left with a width of 20
-
7. Extra space in string
s = ' jackfrued@126.com \t\r\n' # The strip method obtains the string after trimming the left and right spaces of the string print(s) print(s.strip()) # jackfrued@126.com
-
8. Replace the specified character in the string with the specified character
a='hello,world' a_1=a.replace(',',' ') # Convert, to spaces
-
9. Splitting and merging of strings
words =a_1.split() print(words,len(words)) # You can split it at will words=a_1.rsplit() print(words,len(words)) # Split from left to right words=a_1.split(' ',maxsplit=1) # It can be split at most once c=['abc','def','ghi'] print('-'.join(c)) # Merge strings in the list
-
10. Computer coding into language
a='I love you China' b=a.encode('gbk') c=a.encode('utf-8') # GBK < ----- GB2312 (two English words are combined into one Chinese) ---- ascii (English) (so Chinese is 2 bytes and English is 1 byte) # utf-8 coding is an implementation of unicode (universal code). Chinese characters are 3 bytes in utf-8 print(type(b)) print(b) print(c) d=b'\xce\xd2\xb0\xae\xc4\xe3\xd6\xd0\xb9\xfa' e=b'\xe6\x88\x91\xe7\x88\xb1\xe4\xbd\xa0\xe4\xb8\xad\xe5\x9b\xbd' print(d.decode('gbk'),len(d)) print(e.decode('utf-8'),len(e)) # uft-8 is a variable length byte # Numbers and English are one byte # Chinese is three bytes # The expression enmoj is four characters
-
11. String clear code and secret code conversion
message ='i love you' table =str.maketrans('abcdefghijklmnopqrstuvwxyz','defghijklmnopqrstuvwxyzabc') # String conversion is realized through the translate method of string print((message.translate((table))))
4. Assembly
-
1. Create an empty collection
set2 = set() print(set2) # Create an empty collection
-
2. Three characteristics of sets, certainty, mutual anisotropy and disorder
set1 = {1,2,1,2,3,3,4,6} print(type(set1)) print(set1) # Mutual anisotropy, output can only be 1, 2, 3, 4, 6 # print(set[1]) # # Disorder, error will be reported
-
3. Intersection, union, difference set and symmetric difference of sets
set1 = {1, 2, 3, 4, 5} set2 = {2, 4, 6, 8} # Member operation - deterministic (elements are either in or out of the set) # The efficiency of member operation of set is much higher than that of list print(1 in set1) print(1 not in set1) # intersection print(set1 & set2) print(set1.intersection(set2)) # Union print(set1 | set2) print(set1.union(set2)) # Difference set print(set1 - set2) print(set1.difference(set2)) print(set2 - set1) print(set2.difference(set1)) # Symmetry difference print(set1 ^ set2) print((set1 | set2) - (set1 & set2)) print(set1.symmetric_difference(set2))
-
4. Set judgment, true subset, subset, superset
set3 = {1, 2, 3, 4, 5, 6, 7, 8, 9} # Judge true subset print(set1 < set3) print(set1.issubset(set3)) # Judgment subset print(set1 <= set3) # Judgment superset print(set3 > set2) print(set3.issuperset(set2))
-
5. Add elements to the collection, delete elements, and empty elements
# Hash storage is used at the bottom of the collection # The key of hash storage is to design a good hash function to make different objects produce different hash codes as much as possible # Immutable containers cannot be put into the collection, and hash codes cannot be calculated. As a collection element # Hash storage is used at the bottom of the collection. The location of element storage is determined by calculating the hash code of the element, which is an efficient storage scheme. # The key of hash storage is to design a good hash function to ensure that different objects can calculate different hash codes. # Variable containers (list, set, dictionary) cannot calculate hash codes, so they cannot be put into the set as elements of the set set1 = {'apple', 'banana', 'pitaya', 'apple'} # Add element set1.add('grape') set1.add('durian') print(set1) # Delete element set1.discard('pitaya') print(set1.pop()) print(set1.pop()) print(set1) # Empty element set1.clear() print(set1)
5. Dictionary
-
1. Three ways to build a dictionary
student1={'id':'56466', 'name':'ydw', 'sex':'true', 'birthday':'1980-11' } print(student1) student2=dict(id=1002,name='ydx',sex=True) print(student2) # Constructor function dict1 = {i:i**2 for i in range(1,10)} print(dict1) # Generative grammar
-
2... Traverse the keys in the dictionary, the values in the dictionary, and the key value pairs in the dictionary
for key in student1.keys(): print(key) # Traverse keys in the dictionary print('-'*20) for value in student1.values(): print(value) print('-'*20) # Traverse the values in the dictionary for key,value in student1.items(): print(key,value) # Traverse key value pairs
-
3. Member operation and dictionary index (one can add key value pairs and the other will report errors). Dictionary addition and deletion of key value pairs.
student1['address']='Chengdu, Sichuan' print(student1) # How to add a set of key value pairs if there is no corresponding index in the dictionary print(student1.get('age')) print(student1.get('age',20)) print(student1['birthday']) # If you use get, no error will be reported. If not, a null value will be returned (you can specify the default value) del student1['name'] # Delete key value pair # It's best to use get, or judge whether this key exists before outputting
-
4. Update the merge dictionary, delete key value pairs, and find replacement key value pairs
dict1 = {'A': 100, 'B': 200, 'C': 300} dict2 = {'D': 400, 'E': 500, 'A': 600} # Update (merge or update of elements) dict1.update(dict2) print(dict1) print('-'*20) # The delete -- > key must exist. If it does not exist, KeyError will be generated # del dict1['B'] dict1.pop('B') dict1.popitem() # The last key value pair is deleted by default print(dict1) print('-'*20) print(dict1.setdefault('C')) print(dict1.setdefault('K', 10000)) # If the key does not exist in the dictionary, the key will be added and the default value will be set as the default value of the key. If the key exists in the dictionary, the original corresponding value of the key will be read out # , the value of default will not overwrite the existing one print(dict1) # Empty all dict1.clear() print(dict1)
-
5. Through the interface, jason can convert the online data dictionary into our available data
""" example08 - Network access JSON Format data and parse out the required content Modify the download source of the third-party library to the domestic mirror website ---> pip config set global.index-url https://pypi.doubanio.com/simple Third party Library ---> requests ---> pip install requests agreement ---> The rules of conversation to be observed by both sides of communication. HTTP / HTTPS ---> adopt URL Protocol for accessing network resources ---> Hyper-Text Transfer Protocol(Hypertext Transfer Protocol) Request( request) - Respond( response) Author: Hao Date: 2021/7/30 """ import requests # Initiate a request through the get function and get a response resp = requests.get( url='http://api.tianapi.com/guonei/index', params={'key': 'e8c5524dd2a365f20908ced735f8e480', 'num': 30} ) # news_dict = json.loads(resp.text) # Get JSON data from the response and directly convert it into a dictionary news_dict = resp.json() news_list = news_dict['newslist'] for news in news_list: print(news['title']) print(news['url'])