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

Introduction to python3 zero foundation 1 (learning summary)

編輯:Python

Catalog

      • 1、 download Python
      • 2、 Based on using
        • 2.1、 Escape character
        • 2.2、 Case study (input-if--else)
      • One 、 Introduction to basic concepts 1:
        • 1、assert Assertion
        • 2、 see list How to use :
        • 3、 How to use tuples :(tuple)
        • 4、 String built-in methods
        • 5、 String formatting
        • 6、 Sequence
        • 7、 function
          • 7.1、 Embedded functions and closures
          • 7.2、lambda expression ( Anonymous functions )
        • 8、 recursive (recursion)
          • 8.1、 Fibonacci sequence
        • 9、 recursive —— Hanoi ( Steps to resolve )
        • 10、 Dictionaries (dict)
        • 11、 aggregate ( A disorderly )
        • The derived type
        • 12、 file
          • 12.1、 Open the file in read-only mode to read
          • 12.2、 Open the file by reading and writing
          • 12.3、 A simple use ( Split generation file )
        • 13、 file system
          • os Module about files / Directory commonly used function usage :
          • os.path Module on the path of commonly used functions
        • Regular expression patterns
      • Two 、 introduction 2

1、 download Python

1、 Sign in Official website Download the required version package
With window7 For example :
Right click to download the package (Windows x86-64 executable installer) Run as administrator

#!/usr/bin/python3

2、 Based on using

2.1、 Escape character

Before using variables , It needs to be assigned first .
Variable names can include letters 、 Numbers 、 Underline , Cannot start with a number
(\) Escape character # example : let\'s go
If you want to print more special characters in the path , String preceded by r that will do .
example :D:\AIT\work\Software\xftp
have access to

str = r‘D:\AIT\work\Software\xftp’

2.2、 Case study (input-if–else)

Use idle(Python Editor for ),ctrl+n Create a new edit page ,f5 function

import random # random number 
#print( random.randint(1,10) ) # produce 1 To 10 A random number of integer type 
#print( random.random() ) # produce 0 To 1 Between random floating-point numbers 
#print( random.uniform(1.1,5.4) ) # produce 1.1 To 5.4 Between random floating-point numbers , Interval can not be an integer 
#print( random.choice('tomorrow') ) # Randomly select an element from the sequence 
#print( random.randrange(1,100,2) ) # Generated from 1 To 100 The interval is 2 Random integer of 
secret = random.randint(1,3)
print(" A random number for ",secret)
print('-------- strawberry A Work ---------')
temp = input(" Guess the number , Please write down a number :")
guess = int(temp)
while guess != secret:
temp = input(" Wrong guess. , Please enter again :")
guess = int(temp)
if guess == secret:
print(" You got it right !\n" + " Ouch , It's no use guessing right !")
else:
if guess >secret:
print(" The number is big ")
else:
print(" The number is smaller ")
print(" end ^_^")

One 、 Introduction to basic concepts 1:

1、assert Assertion

>>> assert 3>7 #( Assertion : When the latter condition is false , Program crash pop-up exception AssertionError)
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
assert 3>4
AssertionError

2、 see list How to use :

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'fa', 'guess', 'i', 'list1', 'list2', 'list3', 'member', 'member2', 'random', 'secret', 'temp']
>>>
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>>

dir() When a function has no arguments , Returns the variables in the current range 、 List of types of methods and definitions ; With parameters , Return the properties of the parameter 、 Method list .

>>> member = [1, 3, ' good ', 'stree’']
>>> member.append(' well ') # Append one to the end 
>>> member
[1, 3, ' good ', 'stree', 'sdfasdf']
>>>
>>> member.extend([' Oh ',' ah ']) # Append the list to the end 
>>> member
[1, 3, ' good ', 'stree', 'sdfasdf', ' Oh ', ' ah ']
>>>
>>> member.insert(1,'hei') # Where to insert 
>>> member
[1, 'hei', 3, ' good ', 'stree', 'sdfasdf', ' Oh ', ' ah ']
>>>
>>> member[2]
3
>>>
`>>> member.remove(' ah ') # Delete a value 
>>> member
[1, 'hei', 3, ' good ', 'stree', 'sdfasdf', ' Oh ']
>>> ``
>>> del member[1] # Delete the value of a bit 
>>> member
[1, 3, ' good ', 'stree', 'sdfasdf', ' Oh ']
>>>
>>> member.pop() # Function to remove an element from the list ( Default last element ), And returns the value of that element .
' Oh '
>>> member
[1, 3, ' good ', 'stree', 'sdfasdf']
>>> member.pop(0) # You can also specify to move out 
1
>>> member
[3, ' good ', 'stree', 'sdfasdf']
>>> member[1:3] # Copy out 1 To 3 The value of the position does not include 3, You can also use member[:3]、member[1:]、member[:]
[' good ', 'stree']
>>> member
[3, ' good ', 'stree', 'sdfasdf']
>>> member[:3]
[3, ' good ', 'stree']
>>> member[1:]
[' good ', 'stree', 'sdfasdf']
>>> member[:]
[3, ' good ', 'stree', 'sdfasdf']
>>> member2 = member[:] # Copy . If you use member2 = member Words member2 Because of member Change by change .
>>> member2
[3, ' good ', 'stree', 'sdfasdf']
>>>
>>> list1 = [123]
>>> list2 = [234]
>>> list1 < list2
True
>>> list1 = [123, 456]
>>> list2 = [234, 345]
>>> list1< list2 # Compare the first 0 position 
True
>>> list1 * 3
[123, 456, 123, 456, 123, 456]
>>> 123 in list1
True
>>> 123 not in list1
False
>>> 1223 not in list1
True
>>>
>>> list3 = [123, [' Hello ', 123, 'hello'], 234]
>>> ' Hello ' in list3
False
>>> ' Hello ' in list3[1]
True
>>> list3[1]
[' Hello ', 123, 'hello']
>>>
>>> list3[1][1]
123
>>>
>>> list3 *= 5
>>> list3
[123, [' Hello ', 123, 'hello'], 234, 123, [' Hello ', 123, 'hello'], 234, 123, [' Hello ', 123, 'hello'], 234, 123, [' Hello ', 123, 'hello'], 234, 123, [' Hello ', 123, 'hello'], 234]
>>> list3.count(123) #123 stay list Is the number of times 
5
>>>
>>>
>>> list3 = [234, ' Hello ', 123, 'hello']
>>> list3
[234, ' Hello ', 123, 'hello']
>>>
>>> list3.reverse() #list Median inversion 
>>> list3
['hello', 123, ' Hello ', 234]
>>>
>>> list3.index(123) # Returns the position of the parameter in the list , Hit the first of these positions , Default all ranges 
1
>>>
>>> list3*=3
>>> list3
['hello', 123, ' Hello ', 234, 'hello', 123, ' Hello ', 234, 'hello', 123, ' Hello ', 234]
>>> list3.index(123,3,7) # Query range 3~7, in 123 The location of 
5
>>>
>>> list4 = [0,2,3,5,4,7,6,3]
>>> list4.sort() # Sort from small to large 
>>> list4
[0, 2, 3, 3, 4, 5, 6, 7]
>>> list4.sort(reverse=True) # The reverse 
>>> list4
[7, 6, 5, 4, 3, 3, 2, 0]

3、 How to use tuples :(tuple)

Tuples are immutable , Sorting cannot be increased or decreased

>>> tuple1 = (1,2,3,4,5,6,7,8)
>>> tuple1
(1, 2, 3, 4, 5, 6, 7, 8)
>>> tuple1[1]
2
>>> tuple1[3:]
(4, 5, 6, 7, 8)
>>> tuple2 = tuple1[:]
>>> tuple2
(1, 2, 3, 4, 5, 6, 7, 8)
>>>
>>> temp = (3,) # Creating a tuple must have a comma 
>>> type(temp) # See variable types 
<class 'tuple'>
>>>
>>> temp1 = (3)
>>> type(temp1)
<class 'int'>
>>>
>>> tuple1
(1, 2, 3, 4, 5, 6, 7, 8)
>>> tuple1 = tuple1[:2] + ('leo',) + tuple1[2:] # You can use splicing to make changes , Splice old tuples into new ones ( It's actually a change tuple1 Pointer position , Old pointer python It will be cleaned up automatically after a period of time .)
>>> tuple1
(1, 2, 'leo', 3, 4, 5, 6, 7, 8)
>>>
>>> 8 * (8,) # Follow list equally 
(8, 8, 8, 8, 8, 8, 8, 8)
>>>

4、 String built-in methods

Use the built-in method , The original value will not change

>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>
>>> str1 = 'I love you'
>>> str1.capitalize() # title case 
'I love you'
>>> str1.casefold() # 
'i love you'
>>> str1.center(40)
' I love you '
>>> str1.count('o')
2
>>> str1
'I love you'
>>>
>

String built-in methods

Method explain capitalize()# Change the first character of a string to uppercase casefold()# Change all characters of the whole string to lowercase center(width)# Center the string , And fill it with Spaces to length width New string of count(sub[, start[, end]])# return sub The number of occurrences in the string ,start and end Parameters represent ranges , Optional .encode(encoding=‘utf-8’, errors=‘strict’)# With encoding The specified encoding format encodes the string .endswith(sub[, start[, end]])# Check whether the string uses sub End of substring , If it's a return True, Otherwise return to False.start and end Parameters represent ranges , Optional .expandtabs([tabsize=8])# Put... In the string tab Symbol (\t) Convert to space , If no parameter is specified , The default number of spaces is tabsize=8.find(sub[, start[, end]])# testing sub Whether to include in the string , If so, return the index value , Otherwise return to -1,start and end Parameters represent ranges , Optional .index(sub[, start[, end]])# Follow find The method is the same , But if sub be not in string An exception will be generated in .isalnum()# Returns if the string has at least one character and all characters are letters or numbers True, Otherwise return to False.isalpha()# Returns if the string has at least one character and all characters are letters True, Otherwise return to False.isdecimal()# Returns... If the string contains only decimal digits True, Otherwise return to False.isdigit()# Returns if the string contains only numbers True, Otherwise return to False.islower()# If the string contains at least one case sensitive character , And these characters are all lowercase , Then return to True, Otherwise return to False.isnumeric()# If the string contains only numeric characters , Then return to True, Otherwise return to False.isspace()# If the string contains only spaces , Then return to True, Otherwise return to False.istitle()# If the string is heading ( All words begin with uppercase , The rest of the letters are in lowercase ), Then return to True, Otherwise return to False.isupper()# If the string contains at least one case sensitive character , And these characters are all uppercase , Then return to True, Otherwise return to False.join(sub)# Use string as separator , Insert into sub Between all the characters in .ljust(width)# Returns a left aligned string , And fill in the space to the length of width New string of .lower()# Convert all uppercase characters in the string to lowercase .lstrip()# Remove all spaces to the left of the string partition(sub)# Find the substring sub, Break a string into 3 Tuples (pre_sub, sub, fol_sub), If the string does not contain sub Then return to (‘ Original string ’, ‘’, ‘’)replace(old, new[, count])# Put... In the string old Substring is replaced by new Substring , If count Appoint , The substitution does not exceed count Time .rfind(sub[, start[, end]])# Be similar to find() Method , Just search from the right .rindex(sub[, start[, end]])# Be similar to index() Method , It's just from the right .rjust(width)# Returns a right aligned string , And fill in the space to the length of width New string of .rpartition(sub)# Be similar to partition() Method , Just search from the right .rstrip()# Remove the space at the end of the string .split(sep=None, maxsplit=-1)# Without parameters, the default is to slice string with space as separator , If maxsplit Parameters are set , Only separate maxsplit Substring , Returns the list of concatenated substrings after slicing .-1 It means that the whole is divided .splitlines(([keepends]))# Remove line breaks from the output , The default is False, Does not contain line breaks ; If True, Keep the newline ..startswith(prefix[, start[, end]])# Check whether the string uses prefix start , Yes, go back to True, Otherwise return to False.start and end Parameter can specify range check , Optional .strip([chars])# Delete all spaces before and after the string ,chars Parameters can be customized to delete characters , Optional .swapcase()# Flip Case in string .title()# Return to headline ( All words begin with uppercase , The rest of the letters are in lowercase ) String .translate(table)# according to table The rules of ( Can be str.maketrans(‘a’, ‘b’) customized ) Convert characters in a string .upper()# Convert all lowercase characters in a string to uppercase .zfill(width)# Return length is width String , Align the original string to the right , Use... In the front 0 fill .

5、 String formatting

>>> "{0} love {1}.{2}".format("i","python","com")
'i love python.com'
>>> "{a} love {b}.{c}".format(a="i",b="python",c="com")
'i love python.com'
>>> "{
{1}}".format(" No printing ")
'{1}'
>>> '{0:.1f}{1}'.format(27.58,'GB') # The colon marks the beginning of the formatting symbol , Print a fixed-point number one digit after the decimal point 
'27.6GB'
>>>
>>> '%c' '%c' '%c' % (97, 98, 99)
'abc'
>>> '%s' % 'i love you'
'i love you'
>>> '%d + %d - %d' % (5,5,1)
'5 + 5 - 1'
>>>
>>> '%o' % 10
'12'
>>> '%10d' % 10
' 10'
>>> '%010d' % 10
'0000000010'
>>> '%-010d' % 10
'10 '
>>>

String formatting symbol meaning

Symbol explain %c Format characters and their ASCII code %s Formatted string %d Formatted integer %o Format an unsigned octal number %x Formats unsigned hexadecimal Numbers %X Formats unsigned hexadecimal Numbers ( Capitalization )%f Formatted floating point number , Precision after the decimal point can be specified %e Scientific notation for formatting floating - point Numbers %E Work with %e, Scientific notation for formatting floating - point Numbers %g Use... Depending on the size of the value %f or %e%G Work with %g, Use... Depending on the size of the value %f perhaps %E

Format operator auxiliary command

Symbol explain m.nm Is the minimum overall width of the display ,n It's the number of decimal places - For left alignment + Show a plus sign before a positive number (+)# Show... In front of octal ‘0o’, Show in front of hexadecimal number ‘0x’ or ‘0X’0 Fill in the front of the displayed number ‘0’ Instead of spaces

Python The escape character of and its meaning

Symbol explain \’ Single quotation marks \" Double quotes \a The system rings \b Back space \n A newline \t Horizontal tabs (TAB)\v Vertical tabs \r A carriage return \f Page identifier \o The character represented by an octal number \x The character represented by a hexadecimal number \0 Represents a null character \\ The backslash

6、 Sequence

>>> b = 'I love you'
>>> b
'I love you'
>>> b = list(b)
>>> b
['I', ' ', 'l', 'o', 'v', 'e', ' ', 'y', 'o', 'u']
>>> c = (1,1,2,3,4,8,13,21,34) # Tuples 
>>> c = list(c) # Tuple to list 
>>> c
[1, 1, 2, 3, 4, 8, 13, 21, 34]
>>>
>>> max(c)
34
>>> min(c)
1
>>> sum(c)
87
>>>
>>> c.append(2) # Append at the end 2
>>> sorted(c) # Sort , Do not change the source c Sequence 
[1, 1, 2, 2, 3, 4, 8, 13, 21, 34]
>>>
>>> c
[1, 1, 2, 3, 4, 8, 13, 21, 34, 2]
>>> reversed(c) # reverse , The object returned is an iterator 
<list_reverseiterator object at 0x0000000002D1E430>
>>> list(reversed(c)) # Convert to list 
[2, 34, 21, 13, 8, 4, 3, 2, 1, 1]
>>>
>>> c
[1, 1, 2, 3, 4, 8, 13, 21, 34, 2]
>>> enumerate(c)
<enumerate object at 0x000000000303AE00>
>>> list(enumerate(c)) # enumeration 
[(0, 1), (1, 1), (2, 2), (3, 3), (4, 4), (5, 8), (6, 13), (7, 21), (8, 34), (9, 2)]
>>>
>>> b
[3, 4, 6, 7, 8]
>>> list(zip(b,c)) # pack 
[(3, 1), (4, 1), (6, 2), (7, 3), (8, 4)]
>>>

7、 function

Python Call function , If there is no definition above, it cannot be called .

>>> def MyFirstFunction():
print('this is my first function')
print(' Thank you again ')
print(' thank CCTV')
>>> MyFirstFunction()
this is my first function
Thank you again
thank CCTV
>>>
>>>
>>> def MySecondFunction(name, parameter):
' This is the function document '
print(name + ' I like your ' + parameter)
>>> MySecondFunction.__doc__
' This is the function document '
>>> MySecondFunction(name = 'leo', parameter=' technology ')
leo I like your technique
>>>
>>>
>>> def MySecondFunction(name=' everyone ', parameter=' Ability '):
' This is the function document '
print(name + ' I like your ' + parameter)
>>> MySecondFunction()
Everybody, I like your ability
>>>
>>>
>>> def test(*params, exp = 8):
print(' The length of the parameter is ', len(params), exp);
print(' The second parameter is ', params[1]);
>>> test(1,'leo',3,5,74)
The length of the parameter is 5 8
The second parameter is leo
>>>

Example 1:

def MyFirstFunction(price , rate):
' This is the function document '
old_price = 20
print(' local variable old_price:',old_price)
global count # Define global variables 
count = 10
final_price = price * rate
return final_price
old_price = float(input(' Please enter the original price :'))
print(' Global variables old_price:',old_price)
rate = float(input(' Please enter the discount rate :'))
new_price = MyFirstFunction(old_price, rate) # Call function calculation 
print(' The price after discount is :', new_price)
print(' Custom global variables count Use global:',count)

Example 1 Running results

====================== RESTART: F:/python-test/function.py =====================
Please enter the original price :100
Global variables old_price: 100.0
Please enter the discount rate :0.5
local variable old_price: 20
The price after discount is : 50.0
Custom global variables count Use global: 10
>>>
7.1、 Embedded functions and closures
>>> def fun1():
x = 5
def fun2():
nonlocal x # Make x Variable globalization 
x *=x
return x
return fun2()
>>> fun1()
25
>>>
7.2、lambda expression ( Anonymous functions )

range

>>>range(10) # from 0 Start to 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11) # from 1 Start to 11
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5) # In steps of 5
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3) # In steps of 3
[0, 3, 6, 9]
>>> range(0, -10, -1) # negative 
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]

Here are range stay for The use of , Recycle out runoob Every letter of :

>>>x = 'runoob'
>>> for i in range(len(x)) :
... print(x[i])
...
r
u
n
o
o
b
>>>

Built in functions filter Filter out from 0 Start to 9,10 The odd of the numbers

>>> range(10) # from 0 Start to 9
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(filter(None, [1, 0, False, True])) # Filter out "yes" and "no" None Of 
[1, True]
>>>
>>> temp = range(10)
>>> def odd(x):
return x % 2
>>> show = filter(odd, temp) # Filter out odd numbers ( Numbers that are not even )
>>> list(show)
[1, 3, 5, 7, 9]
>>>
>>> list(filter(lambda x : x % 2,range(10))) # Filter out odd numbers ( Numbers that are not even ). Equivalent to the above usage 
[1, 3, 5, 7, 9]
>>>

Built in functions map() Meeting Map the specified sequence according to the function provided .
Machining parameter return sequence

>>> list(map(lambda x : x * 2, range(10)))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>

8、 recursive (recursion)

Example 1: seek 5 The factorial ( iteration )
iteration : It's an activity that repeats the feedback process , Its purpose is usually to approach the desired goal or result . Every repetition of a process is called a “ iteration ”, The result of each iteration will be taken as the initial value of the next iteration .( loop )

def recursion(n):
result = n
for i in range(1, n):
result *= i
return result
number = int(input(' Please enter a positive integer :'))
result = recursion(number)
print('%d The factorial is :%d'% (number, result))

Example 1 Result :

===================== RESTART: F:/python-test/recursion.py =====================
Please enter a positive integer :5
5 The factorial is :120
>>>

Example 2: seek 5 The factorial ( recursive )
recursive , It is to call itself in the process of running .

def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
number = int(input(' Please enter a positive integer :'))
result = factorial(number)
print('%d The factorial is :%d'% (number, result))

Example 2 result

===================== RESTART: F:/python-test/factorial.py =====================
Please enter a positive integer :5
5 The factorial is :120
>>>
8.1、 Fibonacci sequence

Iteration execution speed > Recursive execution speed
Example 1: Iterative implementation

def fab(n):
n1 = 1
n2 = 1
n3 = 1
if n < 1:
print(' Input error :')
return -1
while (n -2) > 0:
n3 = n2 + n1
n1 = n2
n2 = n3
n -= 1
return n3
num = int(input(' Please enter a number :'))
result = fab(num)
if result != -1:
print(' in total %d A little rabbit ' % result)

Example 1 result :

======================= RESTART: F:/python-test/fab_1.py =======================
Please enter a number :30
All in all 832040 A little rabbit was born
>>>

Example 2: Recursive implementation ( Calls itself ) Mathematical function thought

def fab(n):
if n < 1 :
print(' Input error :')
return -1
if n==1 or n ==2:
return 1
else:
return fab(n-1) + fab(n-2)
num = int(input(' Please enter a number :'))
result = fab(num)
if result != -1:
print(' All in all %d A little rabbit was born ' % result)

Example 2: result

======================= RESTART: F:/python-test/fab_2.py =======================
Please enter a number :30
All in all 832040 A little rabbit was born
>>>

9、 recursive —— Hanoi ( Steps to resolve )

def hanoi(n, x , y, z):
if n == 1:
print(x, '- Move to ->', z)
else:
hanoi(n-1, x, z, y) # Before the n-1 A plate from x Move to y On 
print(x, '- Move to ->', z) # Take the last plate from the bottom x Move to z On 
hanoi(n-1, y, x, z) # take y Upper n-1 The plates move to z On 
n = int(input(' Please enter the number of floors of Hanoi tower :'))
hanoi(n, 'x Left column ', 'y Center pillar ', 'z Right column ')

Input 4 Layer results :

====================== RESTART: F:/python-test/hannuota.py =====================
Please enter the number of floors of Hanoi tower :4
x Left column - Move to -> y Center pillar
x Left column - Move to -> z Right column
y Center pillar - Move to -> z Right column
x Left column - Move to -> y Center pillar
z Right column - Move to -> x Left column
z Right column - Move to -> y Center pillar
x Left column - Move to -> y Center pillar
x Left column - Move to -> z Right column
y Center pillar - Move to -> z Right column
y Center pillar - Move to -> x Left column
z Right column - Move to -> x Left column
y Center pillar - Move to -> z Right column
x Left column - Move to -> y Center pillar
x Left column - Move to -> z Right column
y Center pillar - Move to -> z Right column
>>>

10、 Dictionaries (dict)

key value

>>> dict1 = {
' Lining ':' Anything is possible ',' Nike ':'jus do IT',' Adidas ':'imossible is nohing'}
>>> print(' Nike's slogan is :',dict1[' Nike '])
Nike's slogan is : jus do IT
>>>
>>> dict2 = {
1:'ont', 2:'two', 3:'three'} # Create a dictionary 
>>> dict2[2]
'two'
>>> dict3 = {
} # Create an empty dictionary 
>>> dict3
{
}
>>>
>>> dict3 = dict((('f',70), ('i',99), ('3',80),('4',9))) # Create a dictionary 
>>> dict3
{
'f': 70, 'i': 99, '3': 80, '4': 9}
>>>
>>> dict4 = dict( Hello =' All over the world ', The movie =' It's beautiful ') # Create a dictionary 
>>> dict4
{
' Hello ': ' All over the world ', ' The movie ': ' It's beautiful '}
>>>
>>> dict4[' The movie '] = ' What is it? ' # modify key Corresponding value 
>>> dict4
{
' Hello ': ' All over the world ', ' The movie ': ' What is it? '}
>>>
>>> dict4[' Little turtle '] = ' What is it again? ' # Add Dictionary key -value
>>> dict4
{
' Hello ': ' All over the world ', ' The movie ': ' What is it? ', ' Little turtle ': ' What is it again? '}
>>>
>>> dict1 = {
}
>>> dict1
{
}
>>> dict1.fromkeys((1,2,3,4))
{
1: None, 2: None, 3: None, 4: None}
>>> dict1 = dict1.fromkeys(range(32), ' Fabulous ')
>>> dict1
{
0: ' Fabulous ', 1: ' Fabulous ', 2: ' Fabulous ', 3: ' Fabulous ', 4: ' Fabulous ', 5: ' Fabulous ', 6: ' Fabulous ', 7: ' Fabulous ', 8: ' Fabulous ', 9: ' Fabulous ', 10: ' Fabulous ', 11: ' Fabulous ', 12: ' Fabulous ', 13: ' Fabulous ', 14: ' Fabulous ', 15: ' Fabulous ', 16: ' Fabulous ', 17: ' Fabulous ', 18: ' Fabulous ', 19: ' Fabulous ', 20: ' Fabulous ', 21: ' Fabulous ', 22: ' Fabulous ', 23: ' Fabulous ', 24: ' Fabulous ', 25: ' Fabulous ', 26: ' Fabulous ', 27: ' Fabulous ', 28: ' Fabulous ', 29: ' Fabulous ', 30: ' Fabulous ', 31: ' Fabulous '}
>>> for eachkey in dict1.keys(): # Print keys
print(eachkey)
0
1
2
3
……
30
31
>>> for eachkey in dict1.values(): # Print values
print(eachkey)
Fabulous
Fabulous
……
Fabulous
>>> for eachkey in dict1.items(): # Print everything 
print(eachkey)
(0, ' Fabulous ')
(1, ' Fabulous ')
(2, ' Fabulous ')
(3, ' Fabulous ')
……
(31, ' Fabulous ')
>>> print(dict1[31])
Fabulous
>>> print(dict1[32])
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
print(dict1[32])
KeyError: 32
>>>
>>> print(dict4.get(32)) # get Get value 
None
>>> dict4.get(32)
>>> print(dict1.get(3, 'meiyou')) # If there is a value, it can be obtained by normal printing value 
Fabulous
>>> print(dict1.get(32, 'meiyou')) # You can return if it does not exist ‘ No, ’
meiyou
>>>
>>> 31 in dict1 # Use in Find out if the member exists 
True
>>> 32 in dict1
False
>>>
>>> dict1.clear() # Empty dictionary 
>>> dict1
{
}
>>>
# Use clear The relevant dictionary table will be cleared , If you directly empty other associated table data, it still exists , Here is an example 
>>> a = {
'name', 'leo'}
>>> b = a
>>> b
{
'leo', 'name'}
>>> a = {
}
>>> a
{
}
>>> b
{
'leo', 'name'}
>>> a = b
>>> a.clear()
>>> b
set()
>>> a
set()
>>> a = {
1:'noe', 2:'two', 3:'three'}
>>> b = a.copy() # Copy 
>>> b
{
1: 'noe', 2: 'two', 3: 'three'}
>>> c = a # assignment , Just put a label on the same data 
>>> c
{
1: 'noe', 2: 'two', 3: 'three'}
>>>
>>> id(a)
50054720
>>> id(b)
50329216
>>> id(c)
50054720
>>>
>>> c[4] = 'four'
>>> c
{
1: 'noe', 2: 'two', 3: 'three', 4: 'four'}
>>> a
{
1: 'noe', 2: 'two', 3: 'three', 4: 'four'}
>>> b
{
1: 'noe', 2: 'two', 3: 'three'}
>>>
>>> a.pop(4) # Specify to pop up a key value
'four'
>>> a
{
1: 'noe', 2: 'two', 3: 'three'}
>>> a.popitem() # Pop up one randomly key value
(3, 'three')
>>> a
{
1: 'noe', 2: 'two'}
>>> a.setdefault('xiaobai') # Add one key
>>> a
{
1: 'noe', 2: 'two', 'xiaobai': None}
>>> a.setdefault(3, 'five') # Add one key value
'five'
>>> a
{
1: 'noe', 2: 'two', 'xiaobai': None, 3: 'five'}
>>> b = {
' The small white ': 'dog'}
>>> a.update(b) # b Map updates to another dictionary a In the middle 
>>> a
{
1: 'noe', 2: 'two', 'xiaobai': None, 3: 'five', ' The small white ': 'dog'}
>>>

11、 aggregate ( A disorderly )

Is chaotic , Cannot index an element .

>>> set1 = set([1,2,3,4,5,5,5]) # Create a collection to automatically weed out duplicate values 
>>> set1
{
1, 2, 3, 4, 5}
>>>

Immutable set :

>>> num3 = frozenset([1,2,3,4,5]) # Define an immutable set 
>>> num3.add(0)
Traceback (most recent call last):
File "<pyshell#148>", line 1, in <module>
num3.add(0)
AttributeError: 'frozenset' object has no attribute 'add'
>>>

Built-in methods :

>>> num2 = {
1,2,3,4,5,6,7,8}
>>> num2
{
1, 2, 3, 4, 5, 6, 7, 8}
>>> 1 in num2
True
>>> 9 in num2
False
>>> num2.add(9) # add to 
>>> num2
{
1, 2, 3, 4, 5, 6, 7, 8, 9}
>>>
>>> num2.remove(1) # remove 
>>> num2
{
2, 3, 4, 5, 6, 7, 8, 9}
>>>

Example : If you want to eliminate duplicate numbers in the list [1,2,3,4,5,5,3,2,1,0]
Method 1
for Circular judgement

>>> num1 = [1,2,3,4,5,5,3,2,1,0]
>>> num1
[1, 2, 3, 4, 5, 5, 3, 2, 1, 0]
>>> temp = []
>>> for each in num1:
if each not in temp:
temp.append(each)
>>> temp
[1, 2, 3, 4, 5, 0]
>>>

Method 2
Use set set The function automatically removes duplicate numbers , But the set is unordered , Although the repeated numbers are eliminated, the results are out of order

>>> num1 = [1,2,3,4,5,5,3,2,1,0]
>>> num1
[1, 2, 3, 4, 5, 5, 3, 2, 1, 0]
>>> num1 = list(set(num1)) # Use set set The function automatically removes duplicate numbers , But the set is unordered , Although the repeated numbers are eliminated, the results are out of order 
>>> num1
[0, 1, 2, 3, 4, 5]
>>>

The derived type

List derivation

[x*y for x in range(1,5) if x > 2 for y in range(1,4) if y < 3]

His order of execution is :

for x in range(1,5)
if x > 2
for y in range(1,4)
if y < 3
x*y
>>> # List derivation 
>>> a = [i for i in range(100) if not(i % 2) and i % 3]
>>> a
[2, 4, 8, 10, 14, 16, 20, 22, 26, 28, 32, 34, 38, 40, 44, 46, 50, 52, 56, 58, 62, 64, 68, 70, 74, 76, 80, 82, 86, 88, 92, 94, 98]
>>> # Dictionary derivation 
>>> b = {
i:i %2 ==0 for i in range(10)}
>>> b
{
0: True, 1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False}
>>> # Set derivation 
>>> c = {
i for i in [1, 1, 2, 3, 4, 5, 5, 6, 7, 3, 2, 1]}
>>> c
{
1, 2, 3, 4, 5, 6, 7}

12、 file

File open mode :

Turn on mode Perform the operation ‘r’ Open the file read-only ( Default )‘w’ Open the file as a write , The existing file will be overwritten ‘x’ If the file already exists , Opening in this mode raises an exception ‘a’ Open in write mode , If the file exists , Write... At the end ‘b’ Open the file in binary mode ‘t’ Open in text mode ( Default )‘+’ Read write mode ( Can be added to other patterns to use )‘U’ Universal line breaks support

File object method :

File object method Perform the operation f.close() Close file f.read([size=-1]) Read from file size Characters , When not given size Or given a negative value , Read all the remaining characters , Then return... As a string f.readline([size=-1]) Read from the file and return a line ( Include line terminators ), If there is size If defined, return size Characters f.write(str) The string str write file f.writelines(seq) Write string sequence to file seq,seq It should be an iteratable object that returns a string f.seek(offset, from) Move the file pointer in the file , from from(0 Represents the starting location of the file ,1 Represents the current location ,2 End of representative document ) The offset offset Bytes f.tell() Returns the current location in the file f.truncate([size=file.tell()]) Intercept files to size Bytes , The default is to intercept the current position of the file pointer
12.1、 Open the file in read-only mode to read
>>> f = open('F:\\python-test\\ file \\ Heart meridian .txt') # Open file 
>>> f.read(5) # Read file contents , If no value is given, read all , Put the pointer to the end 
' The original Heart Sutra '
>>> f.tell() # Return to location 
9
>>> f.seek(2, 0) # Move the file pointer in the file f.seek(offset, from)(0 Represents the starting location of the file ,1 Represents the current location ,2 End of representative document ) The offset offset Bytes 
2
>>> f.readline() # Read from the file and return a line 
' The original text \u3000 \n'
>>> f.seek(0,0) # Put the pointer to the start position 
0
# It can be read as a list 
>>> lines = list(f)
>>> for each_line in lines:
print(each_line)
The original Heart Sutra
……
# The official recommendation is direct iterative reading ( Efficient )
>>> f.seek(0,0)
0
>>> for each_lin in f:
print(each_lin)
The original Heart Sutra
……
12.2、 Open the file by reading and writing
>>> f = open('F:\\python-test\\ file \\ Heart meridian .txt','w')
>>> f.tell()
0
>>> f.write('I love hello wold') # Open the file as a write , The existing file will be overwritten 
17
>>> f.close()
>>>
>>> f = open('F:\\python-test\\ file \\ Heart meridian .txt','a') # Open in write mode , If the file exists , Write... At the end 
>>> f.read()
>>> f.write('I love hello wold')
17
>>> f.close()
12.3、 A simple use ( Split generation file )

test.txt

 Hello :I love hello wold1
Not good. :I love hello wold2
Hello :I love hello wold3
Not good. :I love hello wold4
Hello :I love hello wold5
=======================
Not good. :I love hello wold6
Hello :I love hello wold7
Not good. :I love hello wold8
Hello :I love hello wold9
=======================
Not good. :I love hello wold0
Hello :I love hello wold~
Not good. :I love hello wold!
Hello :I love hello wold?
Not good. :I love hello wold.

Press ‘ Not good. ’、‘ Hello ’: After that, it is divided and stored in different files , One ==== Split into one file
F:/python-test/file.py

# Save the file 
def save_file(boy, girl ,count):
file_name_boy = 'F:\\python-test\\ file \\' + 'boy_' + str(count) + '.txt'
file_name_girl = 'F:\\python-test\\ file \\' + 'girl_' + str(count) + '.txt'
boy_file = open(file_name_boy, 'w') # Open a file to write 
girl_file = open(file_name_girl, 'w')
boy_file.writelines(boy) # Write string to file “ Sequence ”
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
# Split file 
def split_file(file_name):
f = open(file_name)
boy = []
girl = []
count = 1
for each_line in f:
if each_line[:6] != '======':
# We do string segmentation here 
(role, line_spoken) = each_line.split(':', 1) # Split once , Returns the list of concatenated substrings after slicing .
if role == ' Hello ':
boy.append(line_spoken)
if role == ' Not good. ':
girl.append(line_spoken)
else:
# File split save , meet '======' preservation 
save_file(boy, girl, count)
boy = []
girl = []
count += 1
save_file(boy, girl, count)
f.close()
split_file('F:\\python-test\\ file \\test.txt')

The successful running :

13、 file system

import os
os Module about files / Directory commonly used function usage :
Function name Usage method getcwd() Return to the current working directory chdir(path) Change the working directory listdir(path=’.’) List the file names in the specified directory (’.‘ Represents the current directory ,’…' Represents the directory above )mkdir(path) Create a single level directory , If the directory already exists, throw an exception makedirs(path) Recursively create multi tier directories , If the directory already exists, throw an exception , Be careful :'E:\a\b’ and ’E:\a\c’ It doesn't conflict remove(path) Delete file rmdir(path) Delete single level directory , If the directory is not empty, an exception will be thrown removedirs(path) Recursively delete directories , Try to delete layer by layer from subdirectory to parent directory , If the directory is not empty, an exception will be thrown rename(old, new) Will file old Rename it to newsystem(command) Running the system shell command walk(top) Traverse top All subdirectories below the path , Returns a triple :( route , [ Contains the directory ], [ Include files ]) Here are some definitions commonly used in supporting path operations , Support all platforms os.curdir Refers to the current directory (’.’)os.pardir Refers to the directory above (’…’)os.sep Output OS specific path separators (Win for ’\’,Linux for ’/’)os.linesep The line terminator used by the current platform (Win for ’\r\n’,Linux for ’\n’)os.name Refers to the operating system currently in use ( Include :‘posix’, ‘nt’, ‘mac’, ‘os2’, ‘ce’, ‘java’)

Easy to use :

>>> import os
>>> os.getcwd() # Get the current working directory 
'F:\\python-test'
>>> os.chdir('F:\\python-test\\working') # Change working directory 
>>> os.getcwd()
'F:\\python-test\\working'
>>> os.listdir()
['fab_1.py', 'fab_2.py', 'factorial.py', 'file.py', 'function.py', 'hannuota.py', 'print(ifelse).py', 'recursion.py']
>>> os.makedirs('F:\\python-test\\working\\A\\B')
>>> os.listdir()
['A', 'fab_1.py', 'fab_2.py', 'factorial.py', 'file.py', 'function.py', 'hannuota.py', 'print(ifelse).py', 'recursion.py']
>>> os.curdir
'.'
>>> os.listdir(os.curdir)
['fab_1.py', 'fab_2.py', 'factorial.py', 'file.py', 'function.py', 'hannuota.py', 'print(ifelse).py', 'recursion.py']
>>>
os.path Module on the path of commonly used functions
Function name Usage method basename(path) Remove directory path , Returns the file name alone dirname(path) Remove the filename , Return the directory path separately join(path1[, path2[, …]]) take path1, path2 The parts are combined into a pathname split(path) Split filename and path , return (f_path, f_name) Tuples . If you use the directory completely , It also separates the last directory as a file name , And will not determine whether the file or directory exists splitext(path) Separating file names from extensions , return (f_name, f_extension) Tuples getsize(file) Returns the size of the specified file , Unit is byte getatime(file) Returns the most recent access time of the specified file ( Floating point seconds , You can use time Modular gmtime() or localtime() Function conversion )getctime(file) Returns the creation time of the specified file ( Floating point seconds , You can use time Modular gmtime() or localtime() Function conversion )getmtime(file) Returns the latest modification time of the specified file ( Floating point seconds , You can use time Modular gmtime() or localtime() Function conversion ) The following is the function return True or Falseexists(path) Determine the specified path ( Directory or file ) Whether there is isabs(path) Determine whether the specified path is an absolute path isdir(path) Determine whether the specified path exists and is a directory isfile(path) Judge whether the specified path exists and is a file islink(path) Determine whether the specified path exists and is a symbolic link ismount(path) Determine whether the specified path exists and is a mount point samefile(path1, paht2) Judge path1 and path2 Whether two paths point to the same file

Examples of use :

>>> os.path.basename('F:\\python-test\\working\\factorial.py')
'factorial.py'
>>> os.path.dirname('F:\\python-test\\working\\factorial.py')
'F:\\python-test\\working'
>>>
>>> os.listdir(os.path.dirname('F:\\python-test\\working\\'))
['fab_1.py', 'fab_2.py', 'factorial.py', 'file.py', 'function.py', 'hannuota.py', 'print(ifelse).py', 'recursion.py']
>>>
>>> os.path.split('F:\\python-test\\working\\factorial.py')
('F:\\python-test\\working', 'factorial.py')
>>>
>>> os.path.splitext('F:\\python-test\\working\\factorial.py')
('F:\\python-test\\working\\factorial', '.py')
>>> import time
>>> time.localtime(os.path.getatime('F:\\python-test\\working\\factorial.py'))
time.struct_time(tm_year=2020, tm_mon=11, tm_mday=5, tm_hour=15, tm_min=42, tm_sec=43, tm_wday=3, tm_yday=310, tm_isdst=0)
>>>
>>> os.path.exists('F:\\python-test\\working\\factorial.py')
True
>>> os.path.ismount('F:\\')
True
>>> os.path.ismount('F:\\python-test\\')
False
>>>

Regular expression patterns

Pattern describe ^ Match the beginning of the string $ Match the end of the string .. Match any character , Except for line breaks , When re.DOTALL When the mark is specified , You can match any character that includes line breaks .[…] Used to represent a set of characters , List... Separately :[amk] matching ‘a’,‘m’ or ’k’[^…] be not in [] The characters in :[^abc] Match except a,b,c Other characters .re* matching 0 One or more expressions .re+ matching 1 One or more expressions .re? matching 0 Or 1 Fragments defined by the previous regular expression , Not greedy re{ n} matching n First expression . for example ,"o{2}“ Can't match "Bob" Medium "o”, But it matches "food" Two of them o.re{ n,} Exactly match n First expression . for example ,"o{2,}“ Can't match "Bob" Medium "o”, But it can match. "foooood" All in o."o{1,}“ Equivalent to "o+”."o{0,}“ Is equivalent to "o*”.re{ n, m} matching n To m Next fragment defined by the previous regular expression , Greedy way a| b matching a or b(re) Match the expression in brackets , It also means a group (?imx) Regular expressions contain three optional flags :i, m, or x . Only the areas in brackets are affected .(?-imx) Regular expression off i, m, or x Optional logo . Only the areas in brackets are affected .(?: re) similar (…), But it doesn't mean a group (?imx: re) Use... In parentheses i, m, or x Optional logo (?-imx: re) Do not use... In parentheses i, m, or x Optional logo (?#…) notes .(?= re) Forward positive qualifier . If the regular expression contained , With … Express , When the current position matches successfully , Otherwise failure . But once the contained expression has been tried , The matching engine didn't improve at all ; The rest of the pattern also tries to the right of the qualifier .(?! re) Forward negative definer . Contrary to the positive qualifier ; When the contained expression cannot match at the current position of the string .(?> re) Matching independent patterns , No backtracking .\w Match alphanumeric underline \W Matches non alphanumeric underscores \s Match any white space character , Equivalent to [\t\n\r\f].\S Match any non null character \d Match any number , Equivalent to [0-9].\D Match any non number \A Match string start \Z End of match string , If there is a line break , Matches only the ending string before the line break .\z End of match string \G Match where the last match is done .\b Matches a word boundary , That is, the position between the word and the space . for example , ‘er\b’ Can match "never" Medium ‘er’, But can't match “verb” Medium ‘er’.\B Match non word boundaries .‘er\B’ Can match “verb” Medium ‘er’, But can't match “never” Medium ‘er’.\n, \t, etc. . Match a line break . Match a tab , etc. \1…\9 Matching first n Grouped content .\10 Matching first n Grouped content , If it's matched . Otherwise, it refers to the expression of octal character code .

Two 、 introduction 2

Zero Basics 2

Study address
Data address

Pymongo


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