python beginner level - basic grammar

1, Data type

1. Logical type
Logical type, also known as boolean type, has only two values: 0 and 1, or True and False (False and True). Where False and True are other expressions of 0 and 1. They can directly participate in the operation.

True + 100
False + 100

2. Numerical type
Numeric types include integers and floating point numbers. Numeric operators include: add (+), subtract (-), multiply (*), divide (/).
3. Character type
Character data is generally enclosed in single quotation marks ('') or double quotation marks (""). If the string contains special characters, the backslash \ is used to escape special characters.
You can slice strings.

string = 'ABCDEFGHIJK'
#The syntax of step free slicing is string[star:stop]
string[0]   #Take the string with index number 0 to get A single character 'A'
string[0:2] #Get all strings (excluding 2) in the string where the index starts from 0 to 2, and slice to get the string 'AB'
'''Note: when not specified start When, the default starts from index 0. When not specified stop When,
The last element is taken by default, when start and stop If none is specified, the whole string is obtained'''
#The syntax of slicing with step size is string[start:stop:strip]
string[0:8:2] #Slice to get string 'ACEG'

'''Note: the index sequence number of the string starts from 0,Press[star:stop]The slicing operation is closed on the left and open on the right,
therefore string[0:2]It takes a string string Characters of position index sequence numbers 0 and 1 in'''

In addition, you can also use some functions to operate on strings. Common functions for string operation:

functionmeaning
string.lower()Make all string s lowercase
string.upper()Make all string s uppercase
string.lstrip()Delete the space to the left of string
string.rstrip()Delete the space to the right of string
string.islower()Judge whether all string s are lowercase. If yes, it returns True; otherwise, it returns False
string.isupper()Judge whether the string is all uppercase. If yes, it returns True; otherwise, it returns False
string.isspace()Judge whether the string is a space. If yes, it returns True; otherwise, it returns False
string.isnumeric()Judge whether the string is only composed of numbers. If yes, it returns True; otherwise, it returns False
string.replace('a','#')Replace the character 'a' in the string with '#'
'-'.join([string1,string2])Use the symbol '-' to connect strings string1 and string2
string.partition('sep')Returns the string before, after and after the first occurrence of the separator 'sep' in a string
string.rpartition('sep')Returns the string before the last occurrence of the separator 'sep' in a string, 'sep' and the string after it
string.split(' sep',int)Divide the string by the separator 'sep', return the characters before and after 'sep', and int is the number of divisions
string.rsplit('sep ',int)Divide the string by the separator 'sep', return the characters before and after 'sep', and int is the number of divisions
string.isdigit()Judge whether the string is only composed of numbers. If yes, it returns True; otherwise, it returns False
int(string)Converts a string consisting only of numbers to an integer
float(string)Converts a string consisting of floating-point numbers to floating-point numbers
str(int/float)Convert int and float types to strings

Note: when string.split('sep ', int) and string.rsplit('sep', int) do not specify an int value, their effects are no different. When specifying the int value, string.split('sep ', int) splits string from left to right by separator SEP for int times, and string.rsplit('sep', int) splits string from right to left by separator SEP for int times (all symbols are separators, including spaces).

2, List

1. List introduction
List is a very important data type in Python. The list can contain multiple elements, and the element types can be different. Each element can be any data type, including list (i.e. nesting of list), tuple, dictionary and collection. All elements are contained in a square bracket "[]", and each two elements are separated by commas. A list that does not contain any elements, that is, "[]", is called an empty list.
2. List index
To get the elements of the list, you can use the method of list[index], where index is the index of the element to be accessed. To obtain the sublist of the list, you can use the method of list[beg:end], where beg is the starting index of some elements to be retrieved in the list, and end is the ending index of some elements to be retrieved in the list.

ls = [1,2,3,4,5]  #Definition list ls
ls[3]    #Gets the element with index 3 in the list
ls[0:3]  #Get all elements in the list whose index starts from 0 and ends at 3 (excluding 3), and get the sub list [1,2,3]
ls[:3]   #Equivalent to ls[0:3] 
ls[2:]   #Indicates that fetching starts from the position with index 2 to the last element (including the last element)
ls[:]    #Both beg and end are omitted, indicating that all elements in ls are taken out

Note: in Python, the index of the first list element is 0 instead of 1.
3. List common functions

Function nameeffect
list.append(x)Append element x to the end of the list
list.extend(L)Append all elements in list L to the end of the list to form a new list
list.inser(i,x)Insert the element x where index is i in the list
list.remove(x)Removes the first X element from the list. If x element does not exist, an exception is thrown
list.pop(i)Delete the element with index i and display the deleted element. If i is not specified, the last element will pop up by default
del list[index]Delete the element with index in the list, where [index] can be in the form of [beg:end]
list.clear()clear list
list.index(x)]Returns the position of the first x element. If x does not exist, an error is reported
list.count(x)Count the number of x elements in the list
list.reverse()Reverse the list
list.sort()Sort the list from small to large. To sort from large to small, use list.sort(reverse = True), which is a permanent sort
sorted(list)Sort the list from small to large. To sort from large to small, use sorted(ls,reverse = True), which is a temporary sort
list.copy()Returns a copy of the list

3, Tuple

1. Tuple introduction
Tuple is similar to a list. It can contain multiple elements, and the element types can be different. When writing, every two elements are separated by commas. Unlike the list, all elements of the tuple are written in a pair of parentheses "()", and the elements in the tuple cannot be modified. Tuples that do not contain any elements, that is (), are called empty tuples.
2, Index of tuples
Tuples are indexed in exactly the same way as lists. tuple[index] can be used to access elements in tuples, or tuple[beg:end] can be used to extract some elements in tuples to form a new element group.

x = (1,2,3,4,5)  #Define tuple x mode 1
x = 1,2,3 ,4,5   #Define tuple x mode 2
x[1] #Gets the element with index 1 in tuple x
x[0:3] #Get the elements in the tuple whose index starts from 0 to 3 (excluding 2) to form a new tuple
x[:3] #Equivalent to x[0:3]
x[2:] #Indicates that fetching starts from the position with index 2 to the last element (including the last element)
x[:]  #Both beg and end are omitted, indicating that all elements in x are taken out

In Python, if multiple variables are separated by half width commas, multiple variables are organized in the form of tuple s by default. Therefore, in Python, the interchange of two variables can be written as follows:

x,y = 1,2 #Assign 1 to x and 2 to y
x,y = y,x #Swap the values of x and y

3. Tuple common function

functioneffect
tuple.count(x)Calculate the number of times x appears in the tuple
tuple.index(x)Calculates the position of the first x element

4, Assemble

1, Collection introduction
Similar to tuples and lists, a set can also contain multiple elements of different types, but each element in the set is out of order, the same element is not allowed, and the element must be a hashable object. Hashable objects are those that have__ hash__(self) the object of the built-in function. Data of list, tuple, collection, and dictionary types are not hashable objects, so they cannot be elements in a collection.
Note: (1) the element positions in set are unordered, so the elements cannot be obtained in the way of set[i].
(2) Duplicate data cannot be saved in set, that is, it has the function of filtering duplicate data.
2, Collection creation
All elements in the collection are written in a pair of braces "{}", separated by commas. When creating a set, you can use either {} or set function. The syntax format of the set function is set(iterable). iterable is an optional parameter that represents an iteratable object.
Note: an iteratable object refers to an element that can be returned at one time. For example, string, list and tuple are all iteratable data types.

>>> s1 = set("abcdefg")   #Create collection s1
>>> s2 = set("defghijkl") #Create collection s2
>>> s1
{'d', 'e', 'b', 'c', 'f', 'a', 'g'}
>>> s2
{'l', 'd', 'k', 'e', 'h', 'i', 'f', 'g', 'j'}
>>> s1-s2   #Take out the part of s1 that does not contain s2
{'c', 'b', 'a'}
>>> s2-s1   #Take out the part that does not contain s1 in s2
{'l', 'k', 'h', 'i', 'j'}
>>> s1|s2   #Take out the union of s1 and s2
{'l', 'k', 'e', 'h', 'c', 'f', 'j', 'd', 'b', 'i', 'a', 'g'}
>>> s1&s2   #Take out the intersection of s1 and s2
{'d', 'f', 'g', 'e'}
>>> s1^s2   #Take out the union of s1 and s2, but excluding the intersection
{'l', 'k', 'h', 'i', 'b', 'c', 'a', 'j'}
>>> 'a' in s1 #Determine whether 'a' is in s1
True
>>> 'a' not in s1 #Determine whether 'a' is in s1
False

5, Dictionary

1. Dictionary introduction
dict (Dictionary) is another unordered collection of objects. But unlike a collection, a dictionary is a mapping type, and each element is a key: value pair. Each element in the dictionary is separated by commas, and key and value are separated by colons.
In a dictionary object, the key must be unique, that is, the keys of different elements cannot be the same. In addition, the key must be hashable data, that is, the key cannot be of list, tuple, set, dictionary and other types, and the value can be of any type. A dictionary that does not contain any elements, i.e. {}, is called an empty dictionary.
2. Dictionary creation
You can create a dictionary using either {} or the dict function.
The elements of the five dictionary objects created in the following five ways are identical.

a = {'one':1,'two':2,'three':3} #Create dictionary a
b = dict(one = 1,two = 2,three = 3)#Create dictionary b
c = dict(zip(['one','two','three'],[1,2,3]))#Create dictionary c
d = dict([('one',1),('two',2),('three',3)])#Create dictionary d
e = dict({'one':1,'two':2,'three':3})#Create dictionary e

print(a)
print(b)
print(c)
print(d)
print(e)

Output results:
{'one': 1, 'two': 2, 'three': 3}
{'one': 1, 'two': 2, 'three': 3}
{'one': 1, 'two': 2, 'three': 3}
{'one': 1, 'two': 2, 'three': 3}
{'one': 1, 'two': 2, 'three': 3}

The parameters of the zip function are multiple iteratable objects (lists, etc.), and its function is to package the corresponding elements in different objects into meta groups, and then return the list composed of these tuples.
In Python 3. X, in order to reduce memory, the zip function returns an object, which can be converted into a list through the list function.

print(list(zip(['one','two','three'],[1,2,3])))

Output results:
[('one', 1), ('two', 2), ('three', 3)]

3. Access dictionary elements
Unlike list and other sequence objects, when accessing elements in the dictionary, they cannot be accessed by subscript, but by key.

info = {'name':'Zhang San','age':19,'score':{'python':95,'math':92}} #Create dictionary info
 Mode 1:
print(info['name']) #Output Zhang San
print(info['age']) #Output 19
print(info['score'])#Output {'python': 95, 'math': 92}
print(info['score']['python']) #Output 95
print(info['score']['math']) #Output 92

Mode 2:
print(info.get('name')) #Output Zhang San
print(info.get('age')) #Output 19
print(info.get('score'))#Output {'python': 95, 'math': 92}
print(info.get('score').get('python'))#Output 95
print(info.get('score').get('math'))#Output 92

3. Dictionary operation
Common operations of Dictionary:

info = {'name':'Zhang San','age':19,'score':{'python':95,'math':92}} #Create dictionary info
info.items() #Gets the list of items in the dictionary
info.keys() #Get the key list of the dictionary
info.values() #Gets the value list of the dictionary
info.pop('name') #Pop up the item with key = 'name'
d = info.copy() #Dictionary copy
info['class'] = 1005 #Add key value pair 'class' to Dictionary: 1005
info.clear() #Dictionary element cleanup

6, Sequence

Lists, tuples, and strings are collectively referred to as sequences, and they have the following in common:
(1) Each element can be obtained by index;
(2) The default index value always starts from 0;
(3) A set of elements within a range (such as list[beg,end]) can be obtained by slicing;
(4) There are many operators in common (repetition operator, splicing operator, membership operator)
Some common functions and operators for sequences and their meanings:

Function or operatorsignificance
list(iterable)Convert an iteratable object into a list
tuple(iterable)Converts an iteratable object to a tuple
len(s)Returns the length of s
max()Returns the maximum value in a sequence or parameter set
min()Returns the minimum value in a sequence or parameter set
sum(iterable,start = 0)Returns the sum of the sequence iterable and optional parameters
enumerate()Enumeration to generate a tuple composed of the index value and item value of each element
s+tConnecting sequence s and sequence
sn or nsExtend the sequence s n times

7, Traversal function map

Python's built-in function map() is used to traverse the sequence, operate on each element in the sequence, and finally obtain a new sequence. Its syntax is map (function, iteratable), where function is a function and iteratable is an iteratable object. In Python 3, map(function,iterable) returns an object, which can be converted into a list by list(map(function,iterable)).

1, Combine lambda Function use
a = [1,2,3,4,5]
list(map(lambda a:a+100,a))

Output results:
[101, 102, 103, 104, 105]

2, Use with custom functions
def func(a):
    return a+100
    
if __name__ == '__main__':       
    a = [1,2,3,4,5]
    print(list(map(func,a)))

Output results:
[101, 102, 103, 104, 105]

8, Filter function filter

The built-in function filter() in python is used to filter the elements in the sequence and finally obtain the qualified sequence. Its syntax is filter (function, iteratable), where function is a function and iteratable is an iteratable object. In python 3, like the map function, filter(function,iterable) returns an object, which can be converted into a list by list(filter(function,iterable)).

1, Combine lambda Function use
a = [1,2,3,4,5]
list(filter(lambda a:a>2,a))

Output results:
[3, 4, 5]

2, Use with custom functions
def func(a):
    return a>2
    
if __name__ == '__main__':   
    a = [1,2,3,4,5]
    print(list(filter(func,a)))

Output results:
[3, 4, 5]

9, Cumulative function reduce

The reduce function is used to accumulate all elements in the sequence. Starting with Python 3, when using the reduce function, you need to import it from the functools module. Its syntax is reduce (function, iteratable, start), function is a function with two parameters, iteratable is an iteratable object, and start is the initial value.

from functools import reduce

1, Combine lambda Function use
a = [1,2,3,4,5]
reduce(lambda arg1,arg2:arg1+arg2,a)

Output results:
15

2, Use with custom functions
def func(a,b):
    return a+b
    
if __name__ == '__main__':
    a = [1,2,3,4,5]
    print(reduce(func,a))
Output results:
15

python beginner level - Basic Grammar (1)

Keywords: Python list

Added by mapostel on Mon, 20 Sep 2021 07:37:10 +0300