This paper is the notes and corresponding practice application in the process of self-learning python , I hope it can help you, and I hope you can communicate and learn together
catalogue
3. Reverse iteration and iteration after arrangement
1, for loop -- iteration
1. Iterative dictionary
To traverse all the keywords of the dictionary, you can use the common for statement like traversing the sequence, such as:
d = {"x":1,"y":2,"z":3} for key in d: print(key,"The corresponding value is",d[key])
You can also use dictionary methods such as keys to get all the keys. If you are only interested in values, you can use d.values. You can also use d.items to return key value pairs as tuples. One of the advantages of the for loop is that sequence unpacking can be used in it. For example:
d = {"x":1,"y":2,"z":3} for key,value in d.items(): print(key,"The corresponding value is",value)
2. Some iterative tools
- zip function: you can "stitch" two sequences together and return a sequence composed of tuples. The return value is an object suitable for iteration. To view its contents, you can use list to convert it into a list. After "stitching", tuples can be unpacked in the loop. For example:
a = ['a','b','c'] b = [1,2,3] c = list(zip(a,b)) print(c) for a,b in zip(a,b): print(a,"corresponding",b)
- Get index on iteration
For example, you want to replace all strings containing the substring 'xxx' in a string list
strings = ["mane","2xxx","da"] index = 0 for string in strings: if 'xxx' in string: strings[index] = '[censored]' index +=1 print(strings)
Of course, there is another way, that is to use the built-in function enumerate
strings = ["mane","xxx","da"] for index,string in enumerate(strings): if 'xxx' in string: strings[index] = '[censored]' print(strings)
This function allows you to iterate over index value pairs, where the index is automatically provided.
3. Reverse iteration and iteration after arrangement
Functions: reversed and sorted. They are similar to the list methods reverse and sort, but can be used for any sequence or iteratable object. Instead of modifying the object in place, they return the inverted and sorted version.
print(sorted([4,3,6,8,3])) print(sorted('hello,world!')) print(list(reversed('hello,world'))) print(''.join(reversed('hello,world')))
Note: sorted returns a list, while reversed returns a more mysterious iteratable object like zip. Just use it in methods such as for loop or join, and there will be no problem. You just can't index or slice it, and you can't call list methods directly on it. To perform these operations, first convert the returned object using list.
4. Simple derivation
a = [x * x for x in range(10)] print(a) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
a = [x*x for x in range(10) if x%3 == 0] print(a) # [0, 9, 36, 81]
Note: we choose to use x%3==0 instead of (x*x)% 3 = = 0 because x*x can be divided by 3 only when x can be divided by 3. Therefore, we can talk about code simplification
print([(x, y) for x in range(3) for y in range(3)]) # [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)])
By contrast, the following two for loops create the same list :
result = [] for x in range(3): for y in range(3): result.append((x, y)) print(result)
2, pass, del, and exec
- pass
You can use it as a placeholder when you write code. For example, you might write an if Statement and try to run it, but a code block is missing, which makes these codes unable to run because code blocks cannot be empty in Python. To fix this problem, simply add a pass statement to the middle code block.
a = input("Please enter 1 or 2:") if a == '1': print('1') elif a == '2': pass
Here, when you enter 1, it will print 1. When you enter 2, nothing happens.
- del
x = ["Hello", "world"] y = x y[1] = "Python" del x print(y) print(x)
- exec
exec("print('Hello, world!')")
a = eval(input("Enter an arithmetic expression: ")) print(a)
3, Functions
1. Define function
DEF is used to define functions. Syntax format: def function name ():
You can also define a function with: function name = lambda parameter: return value
For example, write a function to return a list composed of Fibonacci numbers, and you can choose the number of values in the list
def fibs(num): result = [0, 1] for i in range(num-2): result.append(result[-2] + result[-1]) return result print(fibs(10))
2. Position parameters
def function name (formal parameter):
When calling a function, you need to write the actual parameters you call at the corresponding formal parameter position. If you give several parameters when defining, you give them when calling. When calling, you give values in turn according to the sequence of parameter positions, and the positions correspond one by one. For example:
def reduce(a,b): print(a-b) reduce(3,4) #-1
3. Default parameters
You can specify a default value for a parameter. If you do not give a value when calling, the default value will be used; If a parameter is passed during the call, the parameter will override the default value
def reduce(a,b=10): print(a-b) reduce(10,20) # -10 reduce(10) # 0
4. Collect parameters
*args The asterisk in front of the parameter will put all the provided values in a tuple, that is, collect these values
def reduce(*args): # args is a formal parameter print(args) reduce(1,2,3,4,5)
def fun(x, *y, z): print(x, y, z) fun(1, 2, 3, 4, 5, z=7)
When you want to collect keyword parameters, you can use two asterisks. For example:
def reduce(**kwargs): print(kwargs) reduce(a=1,b=2,c=3) # Key and value
What you get is a dictionary, not a tuple
5. Scope
Variables used within functions are called local variables (as opposed to global variables). Parameters are similar to local variables, so there is no problem with parameters having the same name as global variables. For example:
x = 1 def fun(): x = 1 x = x + 1 print(x) fun() print(x)
x = 1 def change_global(): global x x = x + 1 change_global() print(x)
6. View built-in functions
import builtins print(dir(builtins)) # View your current built-in functions