Python notes

Empire my love 2022-05-14 14:53:41 阅读数:326

pythonnotes
'''
Quick notes :ctrl+/
notes :python The note in is shift key +3(#) key , Write the meaning of the code in your own words
Shortcut key (ctrl+/)
Single-line comments : It can be written to the beginning or end of the program
Multiline comment : Three single quotes or three double quotes
Variable : Used to store data
1. Definition of variables grammar Variable name = value
2. The type of variable name 、 Saved data 、 The type of data stored 、 Marked address
3. Variable name and、elif、import、return、as、else、in、try、assert,assert
excep、is、while、assert、except、is,try,break,finally,lambda,with
class、for、not、yidld、continue、from、or、def、global、pass、del、if、raise
character string :
Definition of string , It is also a data type , Also assign values to variables . String cannot be modified or added
Grammar format : Variable name = string('str',"str")
Basic operation of string : Indexes 、 Inquire about 、 Change 、 increase 、 section 、len() Find the length of the string 、 Division
character string 、 Case write 、 Go to space
1. Query Syntax String name (string)[ Subscript number ] note: stay python The subscript of the string inside starts from zero
section : Left closed right open interval [1:9] The following number is not available Grammar format print string[ Subscript number : Subscript number ]
Cut the string and output : Grammar format print string[ Subscript number :] perhaps print string [: Subscript number ]
establish len() Used to find the length of a string :
Grammar format :len( Variable name )
max、min、sum It can only be number type
max() The maximum number ----- Grammar format :print max( Variable name )
min() Minimum number ----- Grammar format :print min( Variable name )
sum() and ----- Grammar format :print sum( Variable name )
note: In Chinese format A Chinese character occupies 3 Characters
A string of Add 、 reduce 、 ride 、 except
Add : It's string splicing Grammar format : Variable name + Variable name
ride : Is a copy of the string Grammar format : Variable name * Numbers
in Used to verify whether a condition is true Grammar format :print Conditions in Variable name Such as ‘a’ in as
note: No subtraction and division
note: stay python The function in is to be called : Variable name .( spot ) Function name ()----- Point reading method
The case of the string : A series of functions used title()
Grammar format : Variable name .title() ----- Capitalize the initial ( The first letter of the word becomes capitalized , The rest becomes lowercase )
Grammar format : Variable name .upper() ----- All capitals
Grammar format : Variable name .lower() ----- All lowercase
Grammar format : Variable name .capitalize()【 The first capital letter is , Other letters remain unchanged 】
blank : stay python Inside , Characters that are not printed are blank 、 As tab (\t)、 A newline (\n)
Delete the blank : Using functions rstrip() Delete the white space character on the right
lstrip() Delete the left margin
strip() Delete the blanks at both ends except
Division : function split() Is to take the space as the boundary , Output the next list
The function of comma is to splice different data types
number: The number
int 、float、long( stay python No, long integer )、bool、complex( The plural ) stay python No, long integer
Numerical operation :% 、 / 、 != 、 += 、 * 、 ** 、 ==
float: It's a numeric type with a decimal point
long: Very long integer
bool: There are two states True、False
compex: The plural has a j(3+4j)
list :type() View the list or view the list type , Create array ----- You cannot assign values outside the bounds
Definition of list :1. Is a data type composed of brackets, including many types of data 、 Can be nested , Use comma as separator
2. Basic operation : Indexes 、 section 、 Additions and deletions 、 Sort
Indexes : and string equally , Subscripts start from zero
Grammar format :print type( Variable name [ Index or subscript ]) ----- View the use of type functions
increase :append()、extend() Add an index or subscript to the array --
Grammar format : Variable name .append( The number ) perhaps Variable name .append( Variable name ( Newly defined and with values ))
Grammar format : Variable name .extend( Conditions )
Delete :del Delete one or more numbers remove Delete the specified number
Grammar format :del List name [ Subscript ] perhaps del List name [ Subscript 1: Subscript 2]
remove( value )
utilize for Loop to output Chinese :
Grammar format :
for i int List name :
print i
modify : Find it first and then modify it
Grammar format : List name [ Subscript ] = value perhaps List name [ Subscript 1: Subscript 2] = value
extend() and append The difference between :
append(): Is to add the elements to be added with ( list ) Add the form to form a list
extend(): Is to add the elements to be added with ( Elements ) Add the form to form a list 
 Insert an element :insert() Usage of : Find the location to insert , Then specify the value
Grammar format :insert( Subscript , value )
pop() The default pop-up is in the last element
Grammar format : List name .pop( Subscript )
String sorting : Permanent sort , Non permanent sort
Permanent sort : be used sort() Method --- Principle if all are numbers, they are sorted according to the size of the first number , Strings are sorted by twenty-six letters
Grammar format : List name .sort()========note: Chinese string type cannot be sorted
In reverse order : Pass a parameter ,
Grammar format : List name .sort (reverse=True)
Non permanent sort :
Grammar format :sorted( List name )
The list of operations
1、 utilize for Loop to output the entire list for.....in......: What has a colon is a code block
2、 Create a list of values range(), Also used for loop
range(start,end,step) note:start The beginning number ,end The number of ends ,step The number of subtractions before and after
Grammar format :for i in range(x,y,step):
print i
list() function Output as list
for i in range(x,y,step):
print i**2 Square value
append()、 extend()、 pop() a key
————————————————————————
Tuples (tuple)
Definition of tuple : Use parentheses to mark the data type in parentheses, which can be any type
The properties of tuples : The data inside cannot be modified , It's a bit like a string
Basic operation : Add delete check 、 section 、 Indexes
Define a tuple of an element :
Grammar format : Tuple name = ( Elements ,)
note: Cannot modify element in tuple , Cannot delete element of tuple
aggregate : Non duplicate data types , Braces are used to mark , If there are duplicate elements, they will be deleted automatically
Basic operation : Addition and subtraction
Dictionaries (dict): Exist as key value pairs , Marked with curly braces 、 In the dictionary, keys cannot be modified , Value can be modified
Grammar format : Dictionary name = {key1:value1,key2:value2,.......}
note: Is an unordered type , The building must be unique , The value does not have to . An index is indexed by a key , Cannot the value corresponding to the index key , The key cannot be a list
characteristic :
1. A colon must be used between key values (:) separate
2. Items must be separated by commas (,) separate
3. The key in the dictionary must be unique , And the value can be repeated
1. Dictionary assignment and dictionary creation
2. Basic operation of dictionary
3. Operator of mapping type
4. Mapping correlation function
5. Dictionary method
One 、 mapping : The input corresponds to the output , The dictionary is python One of the most powerful data types in it
Keys and values are one-to-one correspondence , Is a mapping type 、 Hash value
characteristic : The key is the only 、 Values can be non unique , Think of a dictionary as a container , Satisfy and index , section , Additions and deletions , Can store countless
individual python object type , Lists are dictionaries and sequences that cannot be used as keys :
1. The way of indexing is different
2. The data types accessed and accessed are different
3. The value is preferably in the form of a string ( Although it can be all kinds of data )
4. Dictionaries are arranged out of order
5. Direct mapping from key value to value
dict() function - You can convert a sequence into a dictionary
Variable name 1=[(key,values),(),()]
Grammar format : Variable name 2 = dict( Variable name 1)
View the value of the key : Dictionary name .[ Key name ]
Revise the dictionary : Find the subscript of the modified number , And then modify
Grammar format : Dictionary name [ Key name ]= value
Duplicate keys in the dictionary , The following key will overwrite the previous key
How to add a new element :
Grammar format : Dictionary name [ A new key ] = New value
note: If the input element name is new, it will be added to the dictionary
Delete Dictionary : Delete the specified dictionary or the whole dictionary
note: Cannot access after deleting the entire dictionary
Grammar format :del Dictionary name [ Key name ]
pop Method :
Grammar format : Dictionary name .pop( Key name ) The key name of the pop-up value
note:1. The second key cannot appear , Otherwise, the same key will be assigned twice , The system will select the last value
2. Keys cannot be used with lists , Can be a string 、 Numbers 、 Tuples etc.
len function - Used to calculate the number of dictionary elements or the total number of keys
Grammar format :len( Dictionary name )
type function - Used to return dictionary type or dictionary element type
Grammar format :type( Dictionary name ) perhaps type( Dictionary name [ Element name ( The name of the key )])
dict And list Characteristics :
dict--- Find and insert fast , Not as key The increase slows down
shortcoming : Memory footprint 、 Waste a lot
list--- The search and insertion speed is slow key The increase slows down
shortcoming : Memory footprint 、 Waste little
Dictionary method ;
clear() Method - Used to delete all elements in the dictionary
Grammar format : Dictionary name .clear()
copy() Method - Copy a dictionary
Grammar format : Dictionary name 2 = Dictionary name 1.copy()
fromkeys() Method - Used to create a new dictionary ,seq Key for Dictionary ,value Is the initial value corresponding to the dictionary key
Grammar format : Dictionary name 1 = dict.fromkeys(seq,value=None)
note: If fromkeys Create a new dictionary for keys , Then the corresponding value of the key is None
If seq Is string , Will slice
If seq Is a list of , Will output directly
get() Method - Returns the specified value , Otherwise, it returns the default value None
Grammar format : Dictionary name .get(key,defaull=None)
note:key Representative Key ,default Represents the value corresponding to the key , If not, return the default value None
key in dict Method - Determine whether the key of the dictionary is in the dictionary Just go back to True, Otherwise return to False
Grammar format : Element value in Dictionary name
a. Variable name .has_key() Method , such as :adict.haskey('name') Yes --》True, nothing --》False
b. in、not in such as :'name in adict Yes --》True, nothing --》False
items() Method - Returns an array of tuples nested in a list
Grammar format : Dictionary name .items()
setdefault() Method - Get the key value related to the key , If the key is not in the dictionary, the key is added and the value is set to the default value
Grammar format : Dictionary name .setdefault((key,default=None) perhaps ( key , Key value ))
note:key Represents the key value of the search ,default Represents the default value when the key does not exist . The party
Method has no return value
update Method - Put the dictionary 2 Update to dictionary 1 In
Grammar format : Dictionary name 1.update( Dictionary name 2)
note: If the same key Will be covered
values() Method - Returns all values in the dictionary as a list , The elements in the returned list can contain duplicate elements
Grammar format :list( Dictionary name .values())
keys() Method - Return all the words of a dictionary in a list
Grammar format : Dictionary name .keys()
cmp() Method ; Compare the length
Grammar format :cmp( Dictionary name 1, Dictionary name 2)
note: Dictionary name 1 > Dictionary name 2 return 1
Dictionary name 1 < Dictionary name 2 return -1
Dictionary name 1 = Dictionary name 2 return 0 ( As like as two peas. , The key is the same as the value )
Mapping correlation function :
1.len(): Check the length
2. Factory function dict() Grammar format :dict( Key value pair ) Create a dictionary 
版权声明:本文为[Empire my love]所创,转载请带上原文链接,感谢。 https://pythonmana.com/2022/134/202205141446235815.html