Python Basics - day 5

Keywords: Python encoding Pycharm Attribute

10- iteration

What objects in Python support for loops (or traversal)?
Answer: iteratable objects, or objects that implement the iterator protocol, support traversal or looping. (e.g. list, tuple, dictionary, file). The feature is the internal implementation of the \. Example:

f = open('hello.txt', encoding = 'utf8')
print(f.__next__())
print(f.__next__())
print(f.__next__())
>>>hello, world!

>>>wow!

>>>Hello!

A StopIteration exception is thrown if the \\\\\\\\\.
You can also call the global function next(), as follows:

f = open('hello.txt', encoding = 'utf8')
print(next(f))
print(next(f))
print(next(f))
>>>hello, world!

>>>wow!

>>>Hello!

Similarly, if next() function is called again at this time, StopIteration exception will be thrown.
Note that lists are common iteratable objects, but cannot call the next method and next() global function:

list1 = [1, 2, 3]
print(list1.__next__())
>>>Traceback (most recent call last):
  File "A:/pycharm/python_workspace/01.05/test01.py", line 2, in <module>
    print(list1.__next__())
AttributeError: 'list' object has no attribute '__next__'
list1 = [1, 2, 3]
print(next(list1))
>>>Traceback (most recent call last):
  File "A:/pycharm/python_workspace/01.05/test01.py", line 2, in <module>
    print(next(list1))
TypeError: 'list' object is not an iterator

But why can a list be traversed with a for loop? Because when the list is traversed with the for loop, the system will automatically do one more step. Iteratable objects can be subdivided into iteratable objects and iterator objects. The iteratable object will call the iter() function to generate an iterator when traversing, and the iterator object has already been implemented.
Test: has the file object implemented the iter() function?

f = open('hello.txt', encoding = 'utf8')
print(iter(f) is f)
print(f.__next__())
print(next(f))
>>>True
hello, world!

wow!

The answer is that the file object already implements the iter() function. If so, you can use the next method and the next function directly.
Test: whether the list has implemented the iter() function:

list = [1, 2, 3]
print(iter(list) is list)
>>>False

You cannot call the next method and the next() function at this time. If the for loop is used to traverse the list, the iter() function will be implemented automatically. Can we realize it by ourselves?

list = [1, 2, 3]
i = iter(list)
print(i.__next__())
print(next(i))
>>>1
>>>2

Example, how to cycle manually:

list = [1, 2, 3]
res = []
i = iter(list)
while True:
    try:
        res.append(next(i) ** 2)
    except StopIteration:
        break
print(res)
>>>[1, 4, 9]

2 zip() function
The zip() function is used to take the iteratable object as a parameter, package the corresponding elements in the object into tuples, and then return a list of these tuples.
If the number of elements of each iterator is different, the length of the returned list is the same as that of the shortest object. Using the * operator, the tuple can be decompressed into a list.
The difference between the zip method in Python 2 and python 3: to reduce memory in Python 3.x, zip() returns an object. To display the list, you need to manually convert the list().
If you need to understand the application of Pyhton3, you can refer to Python 3 zip().
zip syntax:
zip([iterable, ...])
Parameter Description:
iterabl - one or more iterators;
Return value
Returns a list of tuples.
Example:

a = [1, 2, 3]
b = [4, 5, 6]
c = [4, 5, 6, 7, 8]
ziped1 = zip(a, b)
ziped2 = zip(a, c) #The number of elements is consistent with the shortest list
print(list(ziped1))
print(list(ziped2))
>>>[(1, 4), (2, 5), (3, 6)]
>>>[(1, 4), (2, 5), (3, 6)]

11 function definition and parameters

The problem of variable scope in Python functions
The variables defined inside the function have a local scope, and the variables defined outside the function have a global scope.
Local variables can only be accessed within the declared function, while global variables can be accessed throughout the program. When a function is called, all variable names declared within the function are added to the scope.

a = 1 #In this case, a is the global variable
print('outside:', id(a))
def func():
    a = 5 #In this case, a is a local variable
    print('inside:', id(a))
func()
print(a) #In this case, a is the global variable
print(id(a))
>>>outside: 8783054934848
>>>inside: 8783054934976
>>>1
>>>8783054934848
a = 1 #In this case, a is the global variable
print('outside:', id(a))
def func():
    global a #Declare a as a global variable
    a = 5 
    print('inside:', id(a))
func()
print(a) #In this case, a is the global variable
print(id(a))
>>>outside: 8783054934848
>>>inside: 8783054934976
>>>5
>>>8783054934976

The related problems of function value transfer
Immutable type, pass copy to function, operation inside function does not affect original value.

def change_num(x):
    x += 10
x = 5
print('x = {}'.format(x))
change_num(x)
print('x = {}'.format(x))
>>>x = 5
>>>x = 5

You can output the changed function values inside the function in the following ways:

def change_num(x):
    x += 10
    return x
x = 5
print('x = {}'.format(x))
x = change_num(x)
print('x = {}'.format(x))
>>>x = 5
>>>x = 15

Variable type, pass address reference, operation in function affects original value.

def change_list(l):
    l[0] = 99
l = [1, 2, 3, 4]
print('Original list:', l)
change_list(l)
print('List after operation:',l)
>>>Original list: [1, 2, 3, 4]
>>>List after operation: [99, 2, 3, 4]
Published 7 original articles, praised 0, visited 74
Private letter follow

Posted by Skull on Sun, 26 Jan 2020 21:14:00 -0800