Python learning the basics - the fifth day

10- iteration

1 python those objects support for loop (or traversing) it?
A: iterable objects, or objects that implement the iterator protocol, or to support traversal cycle. (Such as lists, tuples, dictionaries, file). Characterized implements the __next internal __ () method, the next element can be acquired automatically. Example:

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

>>>wow!

>>>你好!

If a call __next __ () method again, it will raise StopIteration.
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!

>>>你好!

Also, at this time if a call again next () function, it will raise StopIteration.
Note that the list is a common iterable, but it can not be called __next __ () method and the 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 the list can be used for loop through it? Because the list when looping through use for, the system will automatically take the extra step. Iterables can be subdivided into iterables and iterator object . Iterables while traversing calls iter () function to generate an iterator, iterator object while it has been achieved.
Test: whether the file object has been achieved 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 has been achieved iter () function. If so, it can be directly used the __next __ () method and the next () function.
Test: whether the list has been achieved iter () function:

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

At this point you can not call __next __ () method and the next () function. If a for loop through list, then automatically implement iter () function. Can you yourself to achieve it?

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

Examples of how to manually cycle:

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
zip () function can be used for iterative object as a parameter, the corresponding element of the object packed into a tuple and returns a list of these tuples.
If the number of elements of each iterator inconsistency, the shortest length of the list and returns the same object, using the asterisk operator, tuples will extract the list.
Method in different zip 3 Python 2 and Python: Python 3.x in order to reduce the memory, zip () returns an object. To display the list, you need to manually list () conversion.
If you need to understand the application Pyhton3, refer to Python3 zip ().
zip Syntax:
zip ([Iterable, ...])
Parameters:
iterabl - one or more iterator;
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) #元素个数与最短的列表一致
print(list(ziped1))
print(list(ziped2))
>>>[(1, 4), (2, 5), (3, 6)]
>>>[(1, 4), (2, 5), (3, 6)]

11- function definition parameters

1 Python function of the variable scope problem
is defined as having a local scope variables inside a function, defined outside the function has global scope.
The local variables can be declared within its access function, and can access the global variables in the entire program range. When you call a function, all variables declared within a function name will be added to the scope.

a = 1 #此时a为全局变量
print('outside:', id(a))
def func():
    a = 5 #此时a为局部变量
    print('inside:', id(a))
func()
print(a) #此时a为全局变量
print(id(a))
>>>outside: 8783054934848
>>>inside: 8783054934976
>>>1
>>>8783054934848
a = 1 #此时a为全局变量
print('outside:', id(a))
def func():
    global a #声明a为全局变量
    a = 5 
    print('inside:', id(a))
func()
print(a) #此时a为全局变量
print(id(a))
>>>outside: 8783054934848
>>>inside: 8783054934976
>>>5
>>>8783054934976

Problems related transfer function value 2
immutable type, function to transfer a copy operation does not affect the function of the 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

It may be altered by an internal function value output functions in the following manner:

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, delivery address reference value of the operation affect the original function.

def change_list(l):
    l[0] = 99
l = [1, 2, 3, 4]
print('原始列表:', l)
change_list(l)
print('操作后列表:',l)
>>>原始列表: [1, 2, 3, 4]
>>>操作后列表: [99, 2, 3, 4]
Released seven original articles · won praise 0 · Views 93

Guess you like

Origin blog.csdn.net/Mr_Wang0120/article/details/104008858