程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Basic Python operations

編輯:Python

python Basic operation

  • Print
  • Numeric operators
  • The independent variables
  • while
  • for
  • if,ifelse
  • def
  • Function parameter
  • Function default parameters
  • Output function
  • Global local variable
  • Module installation
  • File read and write
  • class
  • class init
  • input
  • Tuples and lists
  • Multidimensional list
  • Dictionaries
  • Loading module
  • continue&break
  • Error handling
  • zip,lambda,map
  • copy&deepcopy
  • pickle
  • set
  • Regular expressions
    • Matching rules
    • Multi-line matching
    • Reuse
    • grouping
    • findall
    • replace
    • split
    • compile

Print

3 Version of print To add (),2.7 And the following versions are not used

Output string Use ’' Single or double quotes print(‘helllo’)

string+string Sure ,string+ Numbers don't work , To bring up numbers or str(4)#

Numeric operators

Square should use ** . 2**2=4 2^2=0

Remainder %

integer // 9//4=2

The independent variables

There is no need to define types for storing arguments a=4

while

condition =1
while condition<10:
print(condition)
condition=condition+1

True False As the capital

Ctrl+C End with

Pay attention to : end

for

A language that values program structure

example_list=[1,1,2,3,4,5,6]//list
for i in example_list:
print(i)

ctrl+[ or ctrl+] Indent

range The iterator automatically generated by the computer should include the header but not the tail

range(1,3) Output [1,2]

range(1,10,2) 1-9 In steps of 2

if,ifelse

x=1;y=2;z=3
if x<y:# Results output 
print('x<y')
if x<y<z:# Results output 
print('x<y<z')
if x<y:
print('x<y')
else:
print('x>y')
if x<y:
print('x<y')
elif:
print('x>y')
else:
print('x>y')

def

Define the equation , Not running , Call is the test

def wpc():
print('this is a test-')
wpc()# Function call 

Function parameter

def wpc(a,b):
c=a+b
print('this is a test-'+str(c))#this is a test-3
print('this is a test-',c)#this is a test- 3
wpc(1,2)# Function call 

When you use a function with parameters , You must pass on the reference or you will make a mistake !

Function default parameters

To solve the problem of too long parameters , Need to write in a separate line

def sale_car(price,color='red',brand='camy',is_second_hand='true'):# Default parameters 
print('price',price,
'color', color,
'brand', brand,
'is_second_hand', is_second_hand,)
sale_car(1000,'red','camy',True)# Cover 
sale_car(13100)

Be careful : Undefined function parameters are put together , The defined function parameters are placed in a block

Output function

def wpc(a,b):
c=a+b
return c
wpc(1,2)# Function call 
print(wpc(2,4))# Output of function value 

Global local variable

It's usually capitalized

APPLE=100# Global variables 
def fun():
global b# Global variables 
b=50
a=APPLE# local variable 
return a+100
print(APPLE)
print(fun())
print(b)
#print(a) Will report a mistake because a Is a local variable 
APPLE=100# Global variables 
a=None
def fun():
a=20
return a+100
print(APPLE)
print('a past=',a)#None Because it still refers to the second row of global variables 
print(fun())#120
print('a now =',a)#None Because it still refers to the second row of global variables , The difference in fun Local variable in a

Module installation

sudo pip3 install numpy // install

sudo pip3 uninstall numpy // uninstall

sudo pip3 install -U numpy // upgrade numpy

sudo Yes, upgrade to administrator

File read and write

Write operations

text = " this is my first test.\n this is next line .\n this is last line"
print(text)
my_file = open('myfile.txt','w')# The first one is the file name , The second is what kind of form 
my_file.write(text)# Write something 
my_file.close()# Remember to close the file 

Additional operations

text = " this is my first test.\n this is next line .\n this is last line"
append_text='\n this is appended file'
print(text)
my_file = open('myfile.txt','a')#a It means to add 
my_file.write(append_text)
my_file.close()

Read operations

file=open('myfile.txt','r')# Save file to file in 
content=file.read()#content It's the content 
print(content)
file=open('myfile.txt','r')
content=file.readline()# Read line by line 
second=file.readline()
all=file.readlines()# Read out the remaining one , With list stored Tabular form 
print(content,second,all)
Running results
this is my first test.
this is next line .
[' this is last line\n', ' this is appended file']

class

It's similar to a function , Variables start with uppercase

class Calculator:# Properties and methods 
name = 'good calculator'
price =18
def add(self,x,y):#self Is itself this class 
print(self.name)
result=x+y
print(result)
def minus(self,x,y):
result = x-y
print(result)
def times(self,x,y):
print(x*y)
def divid(self,x,y):
print(x/y)
calcul =Calculator()# Create a class 
calcul.add(5,4)# Method of using class 

class init

Class has its own functions , Frequently used

class Calculator:# Properties and methods 
name = 'good calculator'
price =18# Common property 
def __init__(self,name,price,hight=3,width=4,weight=5):# initialization , When defining, you must input parameters , There are default parameters 
self.name=name# Given initialization 
self.price=price
self.h=hight
self.w=width
self.we=weight
def add(self,x,y):#self Is itself this class 
print(self.name)
result=x+y
print(result)
def minus(self,x,y):
result = x-y
print(result)
def times(self,x,y):
print(x*y)
def divid(self,x,y):
print(x/y)
calcul =Calculator()# Create a class 
calcul.add(5,4)# Method of using class 

input

a_input =input('give a number')
print('this number is:',a_input)

What the user enters is a string Type oh !!

The solution is int(input())

Tuples and lists

An ordered sequence of numbers

#tupe Tuples list list Are a series of numbers in sequence 
a_tuple=(12,3,5,15,6)# Parenthesis , Or remove the brackets 
another_tuple=2,4,7,6
a_list=[12,3,4,5]
for content in a_tuple:
print(content)
for content in a_list:
print(content)
#tupe Tuples list list Are a series of numbers in sequence 
a_tuple=(12,3,5,15,6)# Parenthesis , Or remove the brackets 
another_tuple=2,4,7,6
a_list=[12,3,4,5]
for index in range(len(a_list)):#range(5) Generate 0,1,2,3,4 Value ,len() length 
print(index)#0,1,2,3
print(a_list[index])#list Start bit 0
a=[1,2,3,4,1,2,3,4]# list 
a.append(0)#.append You can add values 
print(a)# Print out the list 
a.insert(1,0)# stay 1 Add a 0 It's not a modification 
print(a)# Print out the list 
a.remove(2)# Remove the first occurrence 2
print(a)# Print out the list 
print(a[-1])# From back to front is the first for -1
print(a[0:3])# Print 0,1,2 Is the number 
print(a[:3])# Omit 0
print(a[-3:])# Print -3 To the last That is to say -3,-2,-1 position 
print(a)
print(a.index(0))# Print first appears 2 The index of index It's worth 
print(a.count(1))# The value of print statistics is 1 How many numbers are there ?
a.sort()# Sort from small to large , And cover the original list
print(a)
a.sort(reverse=True)# Sort from big to small , And cover the original list
print(a)

Multidimensional list

Multidimensional list, More advanced use numpy,pandas

a=[1,2,3,4,5]
mutil_dim_a=[ [1,2,3],
[2,3,4],
[3,4,5]]
print(a[1])# Output sheet list Of the 2 It's worth 2
print(mutil_dim_a[0][1])# Output 2

Dictionaries

A list is the output in order , The dictionary is out of order

a_list=[1,2,3,4,5,5,4]
d1={
'apple':1,'pear':2,'orange':3}# Need a pair of key values 
d2={
1:'a','c':'d'}
print(d1['apple'])# Output Apple Corresponding value 
print(d1)# Output d1 This dictionary 
del d1['apple']# Delete d1 Medium 'apple' This key is right 
print(d1)# Output d1 This dictionary 
d1['apple']=1# Add a key value pair to the dictionary 
print(d1)# Output d1 This dictionary 
def fun():
print('hello')
d3={
'apple':[1,2,3],# Add... To the dictionary list
'pear': {
'a':1,'b':2 },# Add a dictionary to the dictionary 
'orange':fun}# Add functions to the dictionary 
print(d3)
print(d3['pear']['a'])# Take something out of the dictionary 

Loading module

The official module

# The first 1 Methods 
#import time
#print(time.localtime())
# The first 2 Methods 
#import time as t# in the future time Use both t Instead of 
#print(t.localtime())
# The first 3 Methods 
from time import *# introduce time All functions of 
print(localtime())

Own module

import m1
m1.printdata('hello!!')

continue&break

a=True
while a:
b=input('type')
if b=='1':
# a=False
#break
continue
else:
pass# Don't do anything? 
print('still in run')
print('fininsh run')

Error handling

try:
#file=open('eee','r')# What went wrong , Get into Exception
file=open('eee','r+')# Get into else Error free condition ,r+ It's a read-write operation 
except Exception as e:# The error exists e In this variable , Let's proceed to error handling 
print('there is no file named eee')# Print error messages 
response = input('do you want to create a new file?')
if response=='y':
file=open('eee','w')
else:
pass
else:# If there are no errors, deal with them here 
file.write('sss')
file.close()

zip,lambda,map

map It's the function + Parameters ,lambda Is to simplify the function ,zip It's for iterators

zip

a=[1,3,4]
b=[0,7,8,9]
print(zip(a,b))
print(list(zip(a,b)))# Output [(1, 0), (3, 7), (4, 8)]
# The output of the iterator 
for i,j in zip(a,b):
print(i/2,j*2)
print(list(zip(a,a,b)))# Can output more things 

lambda

def fun1(x,y):
return (x+y)
print(fun1(2,3))
fun2=lambda x,y:x+y# use lambda Define a simple equation 
print(fun2(2,3))

map

def fun1(x,y):
return (x+y)
print(fun1(2,3))
fun2=lambda x,y:x+y# use lambda Define a simple equation 
print(fun2(2,3))
print(map(fun1,[1],[2]))# Output an object ,map( function , Input parameters )
print(list(map(fun1,[1],[2])))
print(list(map(fun1,[1,3],[2,5])))#[1,3] Express x1,x2,[2,5] Express y1,y2

copy&deepcopy

import copy
a=[1,2,3]
b=a# Point to the same space 
print(id(a))# check a The index of 
print(id(b))# check b The index of 
b[0]=11# change b, Change at the same time a
print(a)
print(id(a)==id(b))# return true
c=copy.copy(a)#copy Shallow copy, The first time it's different , Those after the second floor point to the same space 
print(id(a)==id(c))# return false
c[1]=0
print(a)# Don't change 
print(c)
d=[1,2,[3,4]]
e=copy.copy(d)
print(id(d)==id(e))# return false
print(id(e[2])==id(d[2]))# But when list set list In the middle of the day , But it appears id identical 
d[0]=11
print(e)# Change first 
d[2][0]=666
print(e)# change d in list No.1 in , At the same time e
# If you want to be completely copy
f=copy.deepcopy(d)# It won't change at all . The two are completely different 
print(id(f[2])==id(d[2]))

pickle

Save and extract functions

import pickle
a_dict= {
'da':111,
2:[23,1,4],
'23':{
1:2,'d':'sad'}}# Dictionaries 
file=open('pickle_example.pickle','wb')# The suffix of the filename is pickle,wb It's binary 
pickle.dump(a_dict,file)# Like a tractor , hold a_dict Pour to file in 
file.close()
import pickle
a_dict= {
'da':111,
2:[23,1,4],
'23':{
1:2,'d':'sad'}}# Dictionaries 
# file=open('pickle_example.pickle','wb')# The suffix of the filename is pickle,wb It's binary 
# pickle.dump(a_dict,file)# Like a tractor , hold a_dict Pour to file in 
# file.close()
# The first method 
# file= open('pickle_example.pickle','rb')# read 
# a_dict1 = pickle.load(file)# Loading files 
# file.close()
# The second method 
# The problem that the file may be forgotten has not been solved 
with open('pickle_example.pickle','rb') as file:# Automatically help you close the file 
a_dict1 = pickle.load(file) # Loading files 
print(a_dict1)# The content is exactly the same 

set

Help you find a different

char_list = ['a','b','c','c','d','d','d']
print(set(char_list))# result {'d', 'a', 'c', 'b'} Not a dictionary , There is no key value pair 
char_list = ['a','b','c','c','d','d','d']
print(set(char_list))# result {'d', 'a', 'c', 'b'} Not a dictionary , There is no key value pair 
sentence='Welcome to world!'
print(set(sentence))# result {'d', 'c', ' ', 'w', 'm', '!', 'W', 't', 'o', 'l', 'r', 'e'}
# Distinguish between spaces and case 
# Only a single form of list or tuple can be passed , Can't list + list 
char_list = ['a','b','c','c','d','d','d']
print(set(char_list))# result {'d', 'a', 'c', 'b'} Not a dictionary , There is no key value pair 
sentence='Welcome to world!'
print(set(sentence))# result {'d', 'c', ' ', 'w', 'm', '!', 'W', 't', 'o', 'l', 'r', 'e'}
# Distinguish between spaces and case 
# Only a single form of list or tuple can be passed , Can't list + list 
unique_char=set(char_list)
unique_char.add('x')# Add something 
# unique_char.clear()# eliminate set
unique_char.remove('x')# Delete a specific value , Nothing is wrong 
unique_char.discard('z')# Delete value , There is nothing without error 
print(unique_char)
char_list = ['a','b','c','c','d','d','d']
print(set(char_list))# result {'d', 'a', 'c', 'b'} Not a dictionary , There is no key value pair 
sentence='Welcome to world!'
print(set(sentence))# result {'d', 'c', ' ', 'w', 'm', '!', 'W', 't', 'o', 'l', 'r', 'e'}
# Distinguish between spaces and case 
# Only a single form of list or tuple can be passed , Can't list + list 
unique_char=set(char_list)
unique_char.add('x')# Add something 
# # unique_char.clear()# eliminate set
# unique_char.remove('x')# Delete a specific value , Nothing is wrong 
# unique_char.discard('z')# Delete value , There is nothing without error 
set1=unique_char
set2={
'a','e','i'}
print(set1.difference(set2))# Output it has he has nothing Output {'d', 'x', 'b', 'c'}
print(set1.intersection(set2))# Output what it has in common 

Regular expressions

For future reptiles

import re
# matching string
pattern1 = "cat"
pattern2 = "bird"
string = "dog runs to cat"
print(pattern1 in string) # True
print(pattern2 in string) # False
# regular expression
pattern1 = "cat"
pattern2 = "bird"
string = "dog runs to cat"
# It can be seen that , If re.search() Found the result , It will return one match Of object.
# If it doesn't match , It will be returned None. This re.search() It's just re One of the features in 
print(re.search(pattern1, string)) # <_sre.SRE_Match object; span=(12, 15), match='cat'>
print(re.search(pattern2, string)) # None
print('\n')
# multiple patterns ("run" or "ran")
ptn = r"r[au]n" # [ There are two situations ], You need to add a r Used to indicate that this is a regular expression , Instead of ordinary strings 
print(re.search(ptn, "dog runs to cat")) # <_sre.SRE_Match object; span=(4, 7), match='run'>
# Again , brackets [] It can also be the following or a combination of these .
# such as [A-Z] It means all capital English letters . [0-9a-z] The representation can be a number or any lowercase letter .
print(re.search(r"r[A-Z]n", "dog runs to cat")) # None
print(re.search(r"r[a-z]n", "dog runs to cat")) # <_sre.SRE_Match object; span=(4, 7), match='run'>
print(re.search(r"r[0-9]n", "dog r2ns to cat")) # <_sre.SRE_Match object; span=(4, 7), match='r2n'>
print(re.search(r"r[0-9a-z]n", "dog runs to cat")) # <_sre.SRE_Match object; span=(4, 7), match='run'>

Matching rules

In addition to defining their own rules , There are many matching rules that are defined for you in advance . Here are some special matching types for you to summarize , Then give some examples .

  • \d : Any number
  • \D : Not numbers
  • \s : whatever white space, Such as [\t\n\r\f\v]
  • \S : No white space
  • \w : Any upper and lower case letters , Numbers and “” [a-zA-Z0-9]
  • \W : No \w
  • \b : Blank character ( only At the beginning or end of a word )
  • \B : Blank character ( No At the beginning or end of a word )
  • \ : matching first \
  • . : Match any character ( except \n)
  • ^ : Match the beginning
  • $ : Match the end
  • ? : The preceding characters are optional
print(re.search(r"r\dn", "run r4n"))
print(re.search(r"r\Dn", "run r4n"))
print(re.search(r"r\sn", "r\nn r4n"))
print(re.search(r"r\Sn", "r\nn r4n"))
print(re.search(r"r\wn", "r\nn r4n"))
print(re.search(r"r\Wn", "r\nn r4n"))
print(re.search(r"\bruns\b", "dog runs to cat"))
print(re.search(r"\B runs \B", "dog runs to cat"))
print(re.search(r"runs\\", "runs\ to me"))
print(re.search(r"r.n", "r[ns to me"))
print(re.search(r"^dog", "dog runs to cat"))
print(re.search(r"cat$", "dog runs to cat"))
print(re.search(r"Mon(day)?", "Monday"))
print(re.search(r"Mon(day)?", "Mon"))

Multi-line matching

If a string has many lines , We want to use ^ Form to match the characters at the beginning of the line , If it is not successful in the usual form . Like the following “I” Appears at the beginning of the second line , But use r"^I" But it doesn't match the second line , Now , We're going to use Another parameter , Give Way re.search() Each line can be processed separately . This parameter is flags=re.M, Or it can be written like this flags=re.MULTILINE.

string = """ dog runs to cat. I run to dog. """
print(re.search(r"^I", string)) # None
print(re.search(r"^I", string, flags=re.M)) # <_sre.SRE_Match object; span=(18, 19), match='I'>

Reuse

If we want a rule to be repeated , It can also be implemented in regular , And there are many ways to realize . It can be divided into these three types :

  • * : Repeat zero or more times
  • + : Repeat one or more times
  • {n, m} : repeat n to m Time
  • {n} : repeat n Time

Examples are as follows :

# * : occur 0 or more times
print(re.search(r"ab*", "a"))
print(re.search(r"ab*", "abbbbb"))
# + : occur 1 or more times
print(re.search(r"ab+", "a"))
print(re.search(r"ab+", "abbbbb"))
# {n, m} : occur n to m times
print(re.search(r"ab{2,10}", "a"))
print(re.search(r"ab{2,10}", "abbbbb"))

grouping

We can even group what we find , Use () Can easily achieve this . By grouping , We can easily locate what we find . Like here (\d+) In the group , What we need to find is some numbers , stay (.+) In this group , We will find “Date: “ All the rest . When using match.group() when , He will return the contents of all groups , And if you give .group(2) Add a number , It can locate which group of information you need to return .

match = re.search(r"(\d+), Date: (.+)", "ID: 021523, Date: Feb/12/2017")
print(match.group()) # 021523, Date: Feb/12/2017
print(match.group(1)) # 021523
print(match.group(2)) # Date: Feb/12/2017

occasionally , There will be many groups , Using numbers alone may be difficult to find the group you want , Now , If you have a name as an index , It will be a very easy thing . We need to write this form at the beginning of parentheses ?P< name > Just define a name for this group . Then you can use this name to find the content of this group .

match = re.search(r"(?P<id>\d+), Date: (?P<date>.+)", "ID: 021523, Date: Feb/12/2017")
print(match.group('id')) # 021523
print(match.group('date')) # Date: Feb/12/2017

findall

What we said earlier is that we only found the first match , If you need to find all the matches , We can use findall function . And then it goes back to a list . Note that there is a new knowledge point below , | yes or It means , If it weren't for the former, if it weren't for the latter .

# findall
print(re.findall(r"r[ua]n", "run ran ren")) # ['run', 'ran']
# | : or
print(re.findall(r"(run|ran)", "run ran ren")) # ['run', 'ran']

replace

We can also match some forms of strings through regular expressions and then replace them . Use this matching re.sub(), Will compare python Self contained string.replace() Be flexible .

print(re.sub(r"r[au]ns", "catches", "dog runs to cat")) # dog catches to cat

split

Come again Python There is a string segmentation function in , For example, if you want to get all the words in a sentence . such as "a is b".split(" "), This will produce a list of all the words . But in regular , This ordinary segmentation can also be done incisively and exquisitely .

print(re.split(r"[,;\.]", "a;b,c.d;e")) # ['a', 'b', 'c', 'd', 'e']

compile

Last , We can still use compile After the regular , To reuse this regular . Let's start with regular compile Enter a variable , such as compiled_re, Then use this directly compiled_re To search for .

compiled_re = re.compile(r"r[ua]n")
print(compiled_re.search("dog ran to cat")) # <_sre.SRE_Match object; span=(4, 7), match='ran'>

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved