Python quick start notes: day 3

Posted by johnbest on Fri, 06 Mar 2020 06:49:48 +0100

This is a self-study note for preparing for the postgraduate entrance examination. I hope to make a textCNN text sentiment analysis language foundation. The blogger is not a computer major. If the netizens are lucky enough to see this article, if there is any omission in the content of the blog, please give me advice.

Section 4 dictionary

4.1 dictionary definition

   in Python, a dictionary is the most flexible data type other than a list. Dictionaries can also be used to store multiple data, usually used to store information about an object. Unlike lists, dictionary elements are unordered. The dictionary is defined as:

  • The dictionary uses key value pairs to store data, and key value pairs are separated by ",";
  • key is index;
  • value is data;
  • key and value are separated by ":";
  • key must be unique and can only use string, number or tuple, value can go to any data type (Python allows to create an empty dictionary). The specific definition code is as follows:
#Code is grammatically OK
Flag = 0
dict_demo = {
    "name":"Ada",
    Flag:"01",
    ("XYZ","ABC"):("A","X")
}

In the actual development, all key values are used to describe the supplement of dictionary objects. The most commonly used key value type is string. The dictionary can be accessed through the key or the array element in the C language

print(dict_demo[0])
print(dict_demo["name"])

Adding the dictionary key value is very simple. Just add the key you want to add directly to [] or use update(). Using pop() and del statements also removes elements from the dictionary.

dict_demo["Number"] = 100	#At this time, both key and value are added to the dictionary
dict_demo.update({"Number":200})
# Use the update method to pass in a dictionary. If the key exists, the original value will be overwritten
# No will be added to the dictionary

At the same time, for traversal. If the dictionary element name is accessed directly, the corresponding key value pair will be returned; if the key() or value() method is used, the corresponding key and value will be returned.

In actual development, it is often possible to use dictionaries to define objects that do not require order. You can even put multiple dictionaries in one list. Such as:

card_list = [{
			"name":"ZhangSan",
			"qq":1234567,
			"Tel:13812345678"},
			{"name":"LiSi",
			"qq":987654,
			"Tel:13212345678",
			}]

Section 5 functions and modules

5.1 function primary

                       . The function list still needs to be enclosed in parentheses, and the return keyword is used. Specific code examples are as follows:

def function_01(start_num, end_num):
    while start_num <=  end_num:
        function_01(start_num + 1, end_num)
        print("Count down:%d and End:%d" % (end_num, start_num))
        return start_num
function_01(1, 10)

In addition, sometimes when you don't know how many parameters you need, you can use the asterisk "*" to transfer any number of parameters, such as:

def make_pizza(size, *toppings):

    print("\nMaking a " + str(size) +
    "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
from pizza import make_pizza as mp
import pizza as p
import pizza import * //Be similar to java

In addition, you can also use the as keyword to assign aliases to functions and modules, such as "define" in C.

5.2 module

This is similar to the concept of "package" in Java. Just use the import keyword to import the module into the required file, for example:

------------------------------------------------------------------------------------------
# Function in file 1: my mode.py
def show_completed_models(completed_models):
    print("\nThe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)


unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
------------------------------------------------------------------------------------------
#File 2: function call in mode? Demo.py
import my_mode

my_mode.show_completed_models(my_mode.unprinted_designs)
------------------------------------------------------------------------------------------

When learning online, you will also see that part of the code adds the from keyword before the import. This problem will be solved when learning classes.
In addition, when using pysharm, you may encounter the problem of underlining under the file name to be imported when you first import the file using the import keyword:

Just mark the directory folder as: source root directory.

In addition, when learning the book Python from introduction to practice, the corresponding chapter also mentions the concept of list slicing:

5.3 slice

The reason     for the first time in the book is that sometimes you need to disable functions from modifying lists. Even after the list operation, the original list shall be kept for filing. To solve this problem, pass a copy of the list to the function instead of the original. To pass a copy of the list to a function, do the following:

function_name(list_name[:])

But it doesn't seem to be the whole function of slicing.
                       .
   if there is only one ":", the third parameter step=1 by default;
                     .

object[start_index:end_index:step]
# start_index: start index. If omitted, it means starting from the endpoint.
# End? Index: terminate the index. If omitted, it means to the other end.
# Step: number represents step size, default is 1; sign represents direction, default is left to right
# When the direction is reverse, the start index should be greater than the end index, otherwise the data will not be retrieved

Code example:

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Cut single element
print(a[3])

# Cut the 2nd to 5th elements, 3 elements in total
print(a[1:4])

# Step 1, right to left
# From the 9th positive number to the 3rd positive number, there are 6 elements in total
print(a[8:2:-1])

# Step 2, right to left
# From the 9th positive number to the 3rd positive number, there are three elements in the middle
print(a[8:2:-2])

'''
3
[1, 2, 3]
[8, 7, 6, 5, 4, 3]
[8, 6, 4]
'''
print(a[-1:-6:-1])  # From the last 9 to the last 5, the step size is 1 direction negative
print(a[-6:-1:2])   # From the fifth to the last number 5 to the first to the last number 9, the steps are positive in 2 directions
print(a[3::2])      # From the fourth positive number 3 to the end, step size is 2-direction positive
print(a[:7:-1])     # From the penultimate 9 to the positive 8 (penultimate 2), step 1 direction is negative

'''
[9, 8, 7, 6, 5]
[4, 6, 8]
[3, 5, 7, 9]
[9, 8]
'''

Since it's slicing, why does the book say that you can use this sentence to use the "backup" list

function_name(list_name[:])

It's easy to associate that during the "slicing" process, Python creates a new memory address for the new list slice again. You can see it with id():

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(id(a))    # 2152272100224
print(id(a[:])) # 2152301667456

   during the execution of this program, the memory address after slicing is not the same as the list address generated by creation. However, slicing is only a shallow copy. It copies the references of elements in the original list. Therefore, when there are elements of variable length objects, the new list will be subject to the original list.

a = [0, 1, 2, 3]
a.append(a[2:4]) 
print(a) # [0, 1, 2, 3, [2, 3]]
a = [0, 1, 2, 3]
a[::].extend(a[2:4])
print(a) # [0, 1, 2, 3]

After learning the class, there will be more skills to use with slicing. Stay for later study.

5.4 passing any number of arguments in a function

You can use * to pass any number of arguments into a function. The code is as follows:

def make_pizza(size, *toppings):
    print("Making a " + str(size) + " inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)


make_pizza(12, "mushrooms", "green peppers", "extra cheese")

At this time, topping will be regarded as a tuple, and any number of keyword arguments can also be accepted. In this case, a dictionary will be introduced. The code is as follows:

def build_profile(first, last, **user_info):
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.items():
        profile[key] = value
    return profile
user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)
19 original articles published, praised 2, 660 visitors
Private letter follow

Topics: Python Java Asterisk C