Python: basic commands, functions and data structures

Smoke tower like flowers 2021-01-23 03:58:19
python basic commands functions data

Reading guide : This paper deals with Python Make a brief introduction to the basic use of . Limited to space , It is impossible to explain in detail Python Use , Just for the data mining cases involved in this book to use the code for basic explanation . If the reader is in initial contact Python, And use Python The goal is data mining , So I believe that the introduction of this article is quite sufficient for you .

author : Zhang Liangjun Tan Liyun Liu Mingjun Jiang Jianming

source : Huazhang technology

 Zero Basics Python: Basic commands 、 function 、 data structure

01 Operation mode

The sample code in this article uses Python Version is Python 3.6. function Python There are two ways to code :
  • One way is to start Python, Then directly enter the corresponding command in the command window ;
  • Another way is to write the complete code as .py Script , Such as, Then go through... In the corresponding path python perform . The code in the script is as follows :
# hello.pyprint('Hello World!')

The execution result of the script is shown in the figure .

 Zero Basics Python: Basic commands 、 function 、 data structure

▲ Script execution results

When writing scripts , You can add appropriate comments . In every line , You can use the well number “#” To add comments , The way to add a single line comment is as follows :
a = 2 + 3 #  The meaning of this order is to 2+3 The result of is assigned to a

If the comment has more than one line , Can be in two “'''”( Three English status single quotes ) Add comments between , The way to add multiline comments is as follows :
a = 2 + 3''' Here is Python Multiline comments for . Here is Python Multiline comments for .'''

If the script has Chinese ( Chinese comment or Chinese string , Chinese string should be preceded by u), Then you need to indicate the code in the document header , And save the script as utf-8 Coding format , The coding method is as follows :

02 Basic commands

1. Basic operation

A preliminary understanding Python when , Think of it as a handy calculator . Readers can open Python, Try entering the code list 1 The order shown .
  • Code list 1:Python Basic operation
a = 2a * 2a ** 2

Code list 1 The order shown is Python A few basic operations , The first command is assignment , The second command is multiplication , The last command is power operation ( namely a2), These are basically common to all programming languages . however Python Support multiple assignments , The method is as follows :
a, b, c = 2, 3, 4

This multiple assignment command is equivalent to the following command :
a = 2b = 3c = 4

Python Support the flexible operation of string , Such as code list 2 Shown .
  • Code list 2:Python String manipulation
s = 'I like python's + ' very much'  #  take s And ' very much' Splicing , obtain 'I like python very much's.split(' ') #  take s Split by space , Get the list ['I', 'like', 'python']

2. Judgment and circulation

Judgment and loop are the basic commands of all programming languages ,Python The format of the judgment statement is as follows :
if  Conditions 1:     sentence 2elif  Conditions 3:     sentence 4else:     sentence 5

It is important to note that ,Python There is no curly bracket {}, either end sentence , It uses indent alignment as a hierarchical marker for statements . Indents at the same level should correspond one by one , Otherwise, an error will be reported . Here's an example of a bad indentation , Such as code list 3 Shown .
  • Code list 3: Wrong indent
if a==1:    print(a)#  Indent two spaces else:        print('a It's not equal to 1')#  Indent three spaces 

No matter what language , Proper indentation is an elegant programming habit .

Accordingly ,Python The cycle of while Circulation and for loop ,while Loop like code list 4 Shown .
  • Code list 4:while loop
s,k = 0,0while k < 101:#  The cycle is to ask for 1+2+3+...+100    k = k + 1    s = s + kprint(s)

for Loop like code list 5 Shown .
  • Code list 5:for loop
s = 0for k in range(101): #  This cycle is also a process of seeking 1+2+3+...+100    s = s + kprint(s)

Here we see in and range grammar .in It's a very convenient and intuitive grammar , Used to determine whether an element is in the list / Tuple ;range Used to generate a continuous sequence , The general grammar is range(a, b, c), Said to a The first item 、c For tolerances not exceeding b-1 Equal difference sequence of , Such as code list 6 Shown .
  • Code list 6: Use range To generate a sequence of equal differences
s = 0if s in range(4):    print('s stay 0, 1, 2, 3 in ')if s not in range(1, 4, 1):    print('s be not in 1, 2, 3 in ')

3. function

Python use def From defining functions , Such as code list 7 Shown .
  • Code list 7: Custom function
def add2(x):    return x+2print(add2(1)) #  The output is 3

Different from the general programming language is ,Python The function return value of can be in various forms , You can go back to the list , Even return multiple values , Such as code list 8 Shown .
  • Code list 8: Custom functions that return lists and multiple values
def add2(x = 0, y = 0):  #  Defined function , At the same time, define the default value of the parameter     return [x+2, y+2]  #  The return value is a list def add3(x, y):    return x+3, y+3  #  Double return a, b = add3(1,2) #  here a=4,b=5

occasionally , Like definition add2() This kind of simple function , use def To write a formal name 、 It's a little bit cumbersome to calculate and return ,Python Support with lambda For simple function definition “ Inline functions ”, It's a bit like MATLAB Medium “ Anonymous functions ”, Such as code list 9 Shown .
  • Code list 9: Use lambda Defined function
f = lambda x : x + 2  #  Defined function f(x)=x+2g = lambda x, y: x + y #  Defined function g(x,y)=x+y

03 data structure

Python Yes 4 Built in data structures —List( list )、Tuple( Tuples )、Dictionary( Dictionaries ) as well as Set( aggregate ), They can be collectively referred to as containers (Container), Because they are actually some “ thing ” A composite structure , And these “ thing ” It could be a number 、 character 、 A list or some combination of them .

Generally speaking , Anything in the container will do , And the type of elements inside the container is not required to be the same .

1. list / Tuples

Lists and tuples are sequence structures , They are very similar in themselves , But there are some different places .

From the aspect of appearance , There are some differences between a list and a tuple . The list is marked with square brackets , Such as a = [1, 2, 3], Tuples are marked with parentheses , Such as b = (4, 5, 6), The way to access elements in lists and tuples is the same , Such as a[0] be equal to 1,b[2] be equal to 6, wait . I just talked about , Anything in the container will do , therefore , The following definition also holds :
c = [1, 'abc', [1, 2]]'''c It's a list , The first element of the list is an integer 1, The second is the string 'abc', The third is the list [1, 2]'''

functionally , The difference between a list and a tuple is : The list can be modified , And tuples cannot . such as , about a = [1, 2, 3], So the statement a[0] = 0, And I'll put the list a It is amended as follows [0, 2, 3], And for tuples b = (4, 5, 6), sentence b[0] = 1 You're going to report a mistake .

It should be noted that , If you already have a list a, At the same time, I want to copy a, And name it variable b, that b = a It's invalid , Now b just a Another name for ( Or quote ), modify b It will also modify a. The right way to copy should be b = a[:].

The functions associated with lists are list, The functions related to tuples are tuple, Their usage and function are almost the same , It's all about converting an object to a list / Tuples , Such as list('ab') The result is ['a', 'b'],tuple([1, 2]) The result is (1, 2). Some common with list / Tuple related functions are as follows .
  • cmp(a, b): Compare two lists / Elements of tuples
  • len(a): list / Number of tuple elements
  • max(a): Returns a list of / Tuple element maximum
  • min(a): Returns a list of / Tuple element minimum
  • sum(a): Will list / Sum the elements in a tuple
  • sorted(a): Sort the elements of the list in ascending order

Besides , As an object , The list itself comes with many practical methods ( Tuples do not allow modification , So there are few ways ), As shown below .
  • a.append(1): take 1 Add to list a At the end of
  • a.count(1): Statistical list a Medium element 1 Number of occurrences
  • a.extend([1, 2]): Will list [1, 2] The content of is appended to the list a At the end of
  • a.index(1): From the list a Find the first 1 Index position of
  • a.insert(2, 1): take 1 Insert list a The index for 2 The location of
  • a.pop(1): Remove list a The index for 1 The elements of

Last , I can't help but mention “ List of analytical ” This function , It can simplify the code that we operate on the elements in the list one by one . Use append Function to operate on list elements , Such as code list 10 Shown .
  • Code list 10: Use append Function to operate on list elements
a = [1, 2, 3]b = []for i in a:    b.append(i + 2)

Use list parsing for simplicity , Such as code list 11 Shown .
  • Code list 11: Use list parsing for simplicity
a = [1, 2, 3]b = [i+2 for i in a]

Such grammar is not only convenient , And intuitive . This fully embodies Python The humanization of grammar . In this book , We're going to use a lot of this simple code .

2. Dictionaries

Python Introduced “ Make up by yourself ” The concept of convenience . Mathematically speaking , It's actually a mapping . Popular speaking , It's also a list , However, its “ Subscript ” No longer 0 Number at the beginning , It's what you define “ key ”(Key).

The basic way to create a dictionary is as follows :
d = {'today':20, 'tomorrow':30}

there today、tomorrow It's the dictionary “ key ”, It must be the only one in the dictionary , and 20、30 Namely “ key ” Corresponding value . The way to access elements in the dictionary is also intuitive , Such as code list 12 Shown .
  • Code list 12: Visit the elements in the dictionary
d['today']    #  The value is 20d['tomorrow'] #  The value is 30

To create a dictionary , There are other convenient methods , Such as through dict() Function conversion , Or by dict.fromkeys To create , Such as code list 13 Shown .
  • Code list 13: adopt dict perhaps dict.fromkeys Create a dictionary
dict([['today', 20], ['tomorrow', 30]])  #  Is equivalent to {'today':20, 'tomorrow':30}dict.fromkeys(['today', 'tomorrow'], 20) #  amount to {'today':20, 'tomorrow':20}

Many dictionary related functions and methods are the same as the list , I won't repeat it here .

3. aggregate

Python Built in the data structure of collection , This concept is basically consistent with the concept of set in Mathematics , The difference between it and the list is :① Its elements are not repeated , And it's out of order ;② It does not support indexing . Usually we use curly braces {} perhaps set() Function to create a collection , Such as code list 14 Shown .
  • Code list 14: Create set
s = {1, 2, 2, 3}  #  Be careful 2 It will automatically go heavy , obtain {1, 2, 3}s = set([1, 2, 2, 3]) #  similarly , It converts a list to a collection , obtain {1, 2, 3}

Set has certain particularity ( Especially the disorder ), So the set has some special operations , Such as code list 15 Shown .
  • Code list 15: Set operations
a = t | s  # t and s Union b = t & s  # t and s Intersection c = t – s  #  Difference set ( Item in t in , But not here. s in )d = t ^ s  #  Symmetric difference set ( Item in t or s in , But not both )

4. Functional programming

Functional programming (Functional programming) Or functional programming or functional programming , It's a programming paradigm , It treats computer operations as mathematical function calculations , And avoid using program state and mutable objects .

simply , Functional programming is a kind of “ dependent ” Programming , Usually in combination with the above lambda Define functions for scientific calculation , It will be simple and convenient .

stay Python in , Functional programming mainly consists of the use of several functions :lambda、map、reduce、filter, among lambda I've already introduced , Mainly used to customize “ Inline functions ”, So now let's introduce the later one by one 3 individual .

(1)map function

Suppose there is a list a = [1, 2, 3], Add... To each element in the list 2 Get a new list , Use the list parsing I mentioned earlier , We can write this way , Such as code list 16 Shown .
  • Code list 16: Use list parsing to manipulate list elements
b = [i+2 for i in a]

And the use of map We can write functions like this , Such as code list 17 Shown .
  • Code list 17: Use map Function operation list elements
b = map(lambda x: x+2, a)b = list(b)  #  The result is [3, 4, 5]

in other words , Let's first define a function , And then use map Command to apply functions one by one to (map) Every element in the list , Finally, an array is returned .map The command also accepts functions with multiple arguments , Such as map(lambda x,y: x*y, a, b) It means that you will a、b The elements of two lists are multiplied , Return the results to the new list .

Maybe some readers have questions : With list parsing , Why do we have to map Orders ? In fact, the list parsing code is short , But in essence for command , and Python Of for Command efficiency is not high , and map Function to achieve the same function , And more efficient , In principle , Its circular command is C Language speed .

(2)reduce function

reduce It's kind of like map, but map Used to traverse one by one , and reduce For recursive calculation . stay Python 3.x in ,reduce The function has been moved out of the global namespace , Placed in fuctools In the library , Use through from fuctools import reduce introduce reduce. Here's an example , This example can work out n The factorial , Such as code list 18 Shown .
  • Code list 18: Use reduce Calculation n The factorial
from fuctools import reduce#  Import reduce function reduce(lambda x,y: x*y, range(1, n+1))

among range(1, n+1) It's like giving a list , The element is 1~n this n It's an integer .lambda x,y: x*y We construct a binary function , Returns the product of two parameters .

reduce The command first operates on the first two elements of the list as arguments to the function , Then the result of the operation and the third number are used as parameters of the function , And then we take the result and the fourth number as the parameters of the function …… According to this post , Until the end of the list , Return the final result . If you use the loop command , Then write a code list 19 The form shown .
  • Code list 19: Use the loop command to calculate n The factorial
s = 1for i in range(1, n+1):    s = s * i


seeing the name of a thing one thinks of its function , It's a filter , Used to filter eligible elements in the list , Such as code list 20 Shown .
  • Code list 20: Use filter Filter list elements
b = filter(lambda x: x > 5 and x < 8, range(10))b = list(b)  #  The result is [6, 7]

Use filter First you need a return value of bool Function of type , If above “lambda x: x > 5 and x < 8” Defines a function , Judge x Is it greater than 5 And less than 8, And then apply this function to range(10) In every element of , If True, be “ Pick out ” That element , Finally, a list of all the elements that meet the conditions is formed to return .

Of course , Above filter sentence , You can also use list parsing , Such as code list 21 Shown .
  • Code list 21: Use list parsing filter
b = [i for i in range(10) if i > 5 and i < 8]

It's no better than filter Complex sentences . But be careful , We use map、reduce or filter, The ultimate goal is to be concise and efficient , because map、reduce or filter The cycle speed ratio of Python Built in for Cycle or while The cycle is much faster .

04 Import and add of Library

We've already talked about Python Construction and use of basic platform , However, only by default it doesn't load all the features . We need to put more libraries ( Or called a module 、 Bag, etc ) Loading in , You even need to install third-party extension Libraries , To enrich Python The function of , To achieve our purpose .

1. Library import

Python Built in a lot of powerful libraries , Like math math library , It can provide us with more abundant and complex mathematical operations , Such as code list 22 Shown .
  • Code list 22: Use math Libraries do math
import mathmath.sin(1)  #  Calculate the sine math.exp(1)  #  Calculate the index math.pi  #  Built in PI constant 

How to import a library , In addition to direct “import Library name ” outside , You can also create an alias for the library , Such as code list 23 Shown .
  • Code list 23: Use alias to import library
import math as mm.sin(1) #  Calculate the sine 

Besides , If you don't need to import all the functions in the library , You can specifically specify the name of the import function , Such as code list 24 Shown .
  • Code list 24: Import the specified function by name
from math import exp as e #  Import only math In the library exp function , And name it ee(1)  #  Calculate the index sin(1)  #  here sin(1) and math.sin(1) They all make mistakes , Because it wasn't imported 

If all functions in the library are imported directly , Such as code list 25 Shown .
  • Code list 25: Import all functions in the library
#  Direct import math library , That is to get rid of math., But if we introduce a third library like this in large quantities , It is easy to cause naming conflicts from math import *exp(1)sin(1)

We can go through help('modules') Command to get all the module names that have been installed .

2. Import future features (For 2.x)

Python 2.x And Python 3.x The difference is not just in the kernel , It's also part of the implementation of the code . such as , stay Python 2.x in ,print It appears as a statement , Usage for print a; But in Python 3.x in , It appears as a function , Usage for print(a).

To ensure compatibility , The basic code of this article is based on Python 3.x The grammar of , While using Python 2.x Readers of , By introducing future Features in a way compatible with code , Such as code list 26 Shown .
  • Code list 26: Import future features
#  take print In the form of functions , The box print(a) Format output from __future__ import print_function# 3.x Of 3/2=1.5,3//2 Is equal to 1;2.x in 3/2=1from __future__ import division

3. Add third party Library

Python Brought a lot of Libraries , But not necessarily to meet our needs . In terms of data analysis and data mining , We also need to add some third-party libraries to expand its functions . Here is a brief introduction to the third-party library installation .

There are many ways to install third-party libraries , As shown below .
  • Download the source code and install it yourself : Flexible installation , But we need to solve the problem of superior dependence by ourselves
  • use pip Command to install : It's more convenient , Automatically solve the problem of superior dependence
  • use easy_install Command to install : It's more convenient , Automatically solve the problem of superior dependence , Than pip Slightly weak
  • Download the compiled package : It's usually Windows The system provides out of the box executable packages
  • Installation mode of the system :Linux System or Mac The software manager of the system comes with the installation method of some libraries

These installation methods have been used in 《 Dry goods collection ! Read a text 8 Common use Python Library from installation to application 》 In detail .

About author : Zhang Liangjun , Senior big data mining and Analysis Expert 、 Pattern recognition experts 、AI technician . Yes 10 Years of big data mining and analysis experience , Good at Python、R、Hadoop、Matlab And so on , Machine learning, etc AI Technology driven data analysis also has in-depth research .

This article is excerpted from 《Python Data analysis and mining practice 》( The first 2 edition ), Issued under the authority of the publisher .

 Zero Basics Python: Basic commands 、 function 、 data structure

Extended reading 《Python Data analysis and mining practice 》

Recommended language : The best seller is upgraded , The first 1 The sales of the edition exceed 10 Ten thousand volumes , By domestic 100 Other institutions of higher learning use it as teaching materials , At the same time, it is regarded as a classic by the data scientists , Is the accepted standard of fact in this field . The author is in the field of big data mining and analysis 10 Years of engineering practice 、 Experience in teaching and starting a business , Not only master the latest technology and practice methods of the industry , And understand the needs and pain points of students and teachers .
本文为[Smoke tower like flowers]所创,转载请带上原文链接,感谢

  1. Mandatory conversion of Python data type
  2. Django reported an error: 'key' ID 'not found in' xxx '. Choices are: xxx'
  3. Python 400 sets of large video, starting from the right direction to learn, a complete set to you
  4. 只需十四步:从零开始掌握Python机器学习(附资源)
  5. Just 14 steps: Master Python machine learning from scratch (resources attached)
  6. Python|文件读写
  7. 安利一个Python界神奇得网站
  8. Python | file reading and writing
  9. Amway is a marvelous website in Python world
  10. 第二热门语言:从入门到精通,Python数据科学简洁教程
  11. The second popular language: from introduction to mastery, python data science concise tutorial
  12. 以我的亲身经历,聊聊学python的流程,同时推荐学python的书
  13. With my own experience, I'd like to talk about the process of learning Python and recommend books for learning python
  14. 以我的亲身经历,聊聊学python的流程,同时推荐学python的书
  15. With my own experience, I'd like to talk about the process of learning Python and recommend books for learning python
  16. Django url 路由匹配过程
  17. Django URL routing matching process
  18. 强者一出,谁与争锋?与Python相比,C++的运行速度究竟有多快?
  19. Who will fight against the strong? How fast is C + + running compared with Python?
  20. python 学习体会
  21. Experience of learning Python
  22. python7、8章
  23. Chapter 7 and 8 of Python
  24. python bool和str转换
  25. python——循环(for循环、while循环)及练习
  26. python变量和常量命名、注释规范
  27. python自定义异常捕获异常处理异常
  28. python 类型转换与数值操作
  29. python 元组(tuple)和列表(list)区别
  30. 解决python tkinter 与 sleep 延迟问题
  31. python字符串截取操作
  32. Python bool and STR conversion
  33. Python -- loop (for loop, while loop) and Practice
  34. Specification for naming and annotating variables and constants in Python
  35. Python custom exception capture exception handling exception
  36. Python type conversion and numerical operation
  37. The difference between tuple and list in Python
  38. Solve the delay problem of Python Tkinter and sleep
  39. Python string interception operation
  40. Python 100天速成中文教程,GitHub标星7700
  41. Python 100 day quick Chinese course, GitHub standard star 7700
  42. 以我的親身經歷,聊聊學python的流程,同時推薦學python的書
  43. With my own experience, I'd like to talk about the process of learning Python and recommend books for learning python
  44. python爬虫获取起点中文网人气排行Top100(快速入门,新手必备!)
  45. Python crawler to get the starting point of Chinese network popularity ranking Top100 (quick start, novice necessary!)
  46. 【Python常用包】itertools
  47. Itertools
  48. (国内首发)最新python初学者上手练习
  49. (国内首发)最新python初学者上手练习
  50. (first in China) the latest practice for beginners of Python
  51. (first in China) the latest practice for beginners of Python
  52. (数据科学学习手札104)Python+Dash快速web应用开发——回调交互篇(上)
  53. (data science learning notes 104) Python + dash rapid web application development -- callback interaction (Part 1)
  54. (数据科学学习手札104)Python+Dash快速web应用开发——回调交互篇(上)
  55. (data science learning notes 104) Python + dash rapid web application development -- callback interaction (Part 1)
  56. (資料科學學習手札104)Python+Dash快速web應用開發——回撥互動篇(上)
  57. (materials science learning notes 104) Python + dash rapid web application development -- callback interaction (Part 1)
  58. Python OpenCV 图片高斯模糊
  59. Python OpenCV image Gaussian blur
  60. Stargan V2: converse image synthesis for multiple domains reading notes and Python code analysis