Summary of learning python in week 2
The difference between lists and tuples
Tuple is also a sequence composed of multiple elements in a certain order. The difference between tuples and lists is that tuples are immutable types, which means that once variables of tuple type are defined, the elements in them can no longer be added or deleted, and the values of elements can't be modified
Set ()
The definition of set is to "treat certain range, definite and distinguishable things as a whole". Each thing in the set is usually called the element of the set. The collection certainly does not support index operations.
- Disorder: in a set, the position of each element is the same, and the elements are disordered. It determines that the collection is one of the four container types that cannot be operated with subscripts and cannot be subscripted
- Dissimilarity: any two elements in a set are considered to be different, that is, each element can only appear once. The mutuality of sets can be seen by using the len() function
- Certainty: given a set and any element, the element either belongs to or does not belong to the set. The two must be one. Ambiguity is not allowed
Set definition, operation and operation
set1 = {1, 2, 5, 7, 9} set2 ={2, 4, 6, 8} # Member operation - deterministic (elements are either in the set or in the set) # The efficiency of member operation of set is much lower than that of list, because hash storage is used 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) # Symmetry difference print(set1 ^ set2) print((set1|set2) - (set1 - set2)) print(set1.symmetric_difference(set2)) a = 'Mobile Internet | online retailers | fresh ' print(a.split('|')) set3 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} # Judge true subset print(set1 < set2) # Judgment subset print(set1 <= set2) # Judging subsets, print(set3 > set2)
Elements in the collection must be of type hashable. The so-called hashable type refers to the data type that can calculate the hash code. You can temporarily understand the hash code as the unique ID value corresponding to the variable. Generally, immutable types are hashable types, such as integer, floating point, string, tuple, etc., while variable types are not hashable types. Because variable types cannot determine the unique ID value, they cannot be put into the collection
The bottom layer of the set in Python uses hash storage. We will not introduce this for the time being. We will explain the bottom principle of the set when necessary in the later courses. At this stage, you only need to know that the set is a container and the elements must be of hashable type. The difference from the list is that the elements in the set have no order and cannot be indexed Cannot repeat. Use the hash function to calculate the address. The designed hash function allows different objects to generate different hash codes as much as possible to reduce hash conflicts (put them into a list). It does not depend on the scale of the problem and is a storage scheme with constant time complexity. If an object cannot design a hash code, it cannot be put into the collection, and the list cannot calculate the hash object.
random.choices() # Randomly selected elements ''.join() # Splice dictionaries, lists, tuples, with spaces
Conversion between lists, tuples, sets, dictionaries
nums = [1, 1, 10, 10, 10, 5, 3, 9, 9] set2 = set(nums) print(set2) list3 = list(set2) print(list3) tuple4 = tuple(list3) print(tuple4) dict5 = dict(tuple4)
Immutable set
Python also has a collection of immutable types called frozenset. The difference between set and frozenset is just like the difference between list and tuple. Because frozenset is an immutable type, it can calculate the hash code, so it can be used as an element in set. In addition to not adding and deleting elements, frozenset is basically the same as set in other aspects. The following code simply shows the usage of frozenset.
set1 = frozenset({1, 3, 5, 7}) set2 = frozenset(range(1, 6)) print(set1 & set2) # frozenset({1, 3, 5}) print(set1 | set2) # frozenset({1, 2, 3, 4, 5, 7}) print(set1 - set2) # frozenset({7}) print(set1 < set2) # False
Dictionary (dict)
Element is composed of key and value. The one before colon is called key and colon
The following are called values, which together are called key value pairs. Use {} literal grammar, which is the same as the collection in the previous lesson. However, the elements in {} of the dictionary exist in the form of key value pairs. Each element is composed of two separated values, * * *: preceded by the key (must be an immutable type), and followed by the value * * *.
person = { 'name': 'Da Chui Wang', 'age': 55, 'weight': 60, 'office': '62 Kehua North Road', 'home': 'No. 8, zhongtongren Road', 'tel': '13122334455', 'econtact': '13800998877' 'contacts':{'qq':'957658','tel':'13548041193'} } print(person) print(person['name']) # Get the value corresponding to the key for contact in person['contacts']: print(contact) dict1 = {} # Literal grammar, empty dictionary
Dictionary construction
# Constructor function students = dict(id=100, name='Da Chui Wang', sex=True, birthday='1980-11') # Generative (deductive) grammar list1 = [i for i in range(1, 10)] print(list1) set1 = {i for i in range(1, 10)} print(set) dict1 = {i: i**2 for i in range(1, 10)} print(dict1) # The difference between the latter two is a colon, none is a set, and some are dictionaries # generator gen_onj = (i for i in range(1, 10)) # It is not a tuple, and the relative functions need to be taken out one by one for value i gen_obj: print(value) # It is generated for you when you use it, unlike the one given to you above # print(next(gen_obj)) print(type(x))
Dictionary traversal
print(len(students)) # Get dictionary elements # Loop to key for key in students: # for key in students.keys(): the two expressions are the same print(students[key]) # Traverse keys and take values (through square bracket index operation) # Loop to value print(students.values()) # Take out all values for value in students.values(): print(value) # Loop to key value pair for key,value in students.items(): print(key, value)
Dictionary operation
# Member operation (in / not in) students = dict(id=100, name='Da Chui Wang', sex=True,birthday='1980-1-1') # The index operation of the dictionary is placed to the left of the assignment operator # If the key corresponding to the index exists, its value is updated students['id'] = 100 students['sex'] = False # Without this key, add this key and assign the corresponding value students['address'] = 'Chengdu, Sichuan' print(students) print('name' in students) print('age' in students) print('address' in students)
The sequence of program statement code should be correct: try... expect Or get() function
while True: try: a, b, c = map(float, input('Please enter: ').split()) print(a, type(a)) print(b, type(b)) print(c, type(c)) break except ValueError: print('Input error, please re-enter!!!') # When using the get function to obtain value through key, if the key does not exist, no exception error will occur # Instead, you get a null value print(students.get('age')) # Or get the default value you specify print(students.get('age',20)) print(students['name']) print(students['birthday']) # Delete key value pair del student['name'] print(students.pop('name')) print(student.get('name', 'anonymous person')) # The proposed algorithm is quite robust # If you use a subscript (index) operation, you must ensure that the key must exist if 'birthday' in student: print(student['birthday'])
Dictionary related operations
Hash storage is used, which can save many values and is very convenient to take values
dict1 = {'A': 100, 'B': 200, 'C': 300} dict2 = {'D': 400, 'E': 500, 'A': 600} # Merging cannot be spliced with + # Update dictionary update() function dict1.update(dict2) # To delete an element, the given key must exist. If it does not exist, KEyError will be generated del dict1['B'] dict1.pop('C') dict1.popitem() # Execute last, delete last stu2 = dict1.pop('C',{}) print(stu2) # Returns 300. If the key value does not exist, returns {} # The key value exists and returns the original value # If the key value does not exist, add and execute the key value pair, or return None dict1.setdefault('C',800) # Empty dictionary dict1.clear() print
Caesar cipher
"""Caesar cipher - A way to encrypt plaintext through corresponding character replacement abcdefghijklmnopqrstuvwxyz defghijklmnopqrstuvwxyzabc Plaintext: attack at dawn Ciphertext: dwwdfn dw gdzg Symmetric encryption: encryption and decryption use the same key ---> AES Asymmetric encryption: encryption and decryption use different keys (public key, private key)--> RSA -->Suitable for Internet applications. """ message = 'attack at dawn.' # Encrypt with str.maketrans() function table = str.maketrans('abcdefghijklmnopqrstuvwxyz','defghijklmnopqrstuvwxyzabc') # Use object The translate (in the list of encryption rules) function performs decryption print(message.translate(table))
Encoding and decoding
""" str((string) ----> encode ----> decode example04 - String operation Encoding: converting one character set into another 1. When selecting a character set (encoding), the best choice (and the default) is UTF -8 code 2. The character set of encoding and decoding should be consistent, otherwise there will be garbled code 3. out-of-service ISO-8850-1 Code save Chinese, otherwise there will be a coding black hole, and Chinese will become? 4. UTF -8 yes unicode It is also a variable length coding. Minimum 1 byte (English and numeric), maximum 4 bytes( Emoji),3 bytes for Chinese. """ a = 'I love you China' b = a.encode('gbk') print(b) print(len(b)) # The corresponding character can correspond to several bytes through len() c = b'\xce\xd2\xb0\xae\xc4\xe3\xd6\xd0\xb9\xfa' print(c.decode('gbk')) # When bytes and characters do not correspond, an abnormal error occurs # utf-8 is commonly used # When there is nothing in encode() and decode (), utf-8 is the default # UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-9: ordinal not in range(256) # The latin -1 code cannot be used to process Chinese, and a black hole will appear
String in JSON format
""" Operating system: Windows,iOS,Android,macOS,Linux,Unix programing language: Python,Java,PHP,Go,C++ 1. The best choice for exchanging data between two heterogeneous systems is to exchange plain text (which can shield the differences between the system and the programming language) 2. Plain text should be structured or semi-structured plain text (with a certain format) ~ XML ---> eXtensible Markup Language ---> Extensible markup language ~ JSON ---> JavaScript Object Notation ---> Most web sites and data interface services use data formats ~ YAML ---> Yet Another Markup Language 3. How will JSON Format string to Python Dictionary in program? ---> json modular ---> loads function URL ---> Universal Resource Locator ---> Uniform resource locator """ import requests laji_name = input('Please enter the garbage Name:') resp = requests.get( url='http://api.tianapi.com/txapi/lajifenlei/index', params={'key': '2cb5b10171d22edd71fac83e9354fa25', 'word':laji_name, 'num':30} ) news_dict = resp.json() news_list = news_dict['newslist'] for news in news_list: print(news['name']) print(news['explain'])