The function name, the iterator

Use function name

The function name is a variable, but it is a special variable, with brackets with variable functions can be executed

1.函数名的内存地址
def func():
    print("hehe")
print(func)
结果:<function func at 0x1101e4ea0>
2.函数名可以赋值给其他变量
def func():   
    print("呵呵")
    print(func)
a = func    # 把函数当成一个值赋值给另一个变量
a()     # 函数调用 func()
3.函数名可以当做容器类的元素
def func1():   
    print("呵呵")
def func2():   
    print("呵呵")
def func3():   
    print("呵呵")
def func4():  
     print("呵呵")
lst = [func1, func2, func3]
for i in lst:  
     i()
4.函数名可以作为函数返回值
def func_1():   
    print("这里是函数1")   
    def func_2():       
        print("这里是函数2")   
    print("这里是函数1")   
    return func_2
fn = func_1()  
# 执行函数1.  函数1返回的是函数2, 这时fn指向的就是上面函数2
fn()    # 执行func_2函数


f-string string formatted

f-strings are added to the standard library python3.6 start new wording formatted output, high-output ratio before the formatting efficiency% s and more simplified format or

Structures is F (f) + str form of, want to replace with the position in the string {} stands, with similar format, but with the end of the string is written alternative content, but he can directly recognize.

name = "小白"
age = 18
sex = "男"
msg = F'姓名:{name},性别:{age},年龄:{sex}'  # 大写字母也可以
msg = f'姓名:{name},性别:{age},年龄:{sex}'  
print(msg)
'''
输出结果:
姓名:小白,性别:18,年龄:男

任意表达式:
print(f'{3*21}') #63
name = 'barry'
print(f"全部大写:{name.upper()}")  #全部大写BARRY

# 字典也可以
teacher = {'name': '', 'age': 18}
msg = f"The teacher is {teacher['name']}, aged {teacher['age']}"
print(msg)  # The comedian is   , aged 18

# 列表也行
l1 = ['', 18]
msg = f'姓名:{l1[0]},年龄:{l1[1]}.'
print(msg)  # 姓名:,年龄:18.

# 插入表达式
def sum_a_b(a,b):
    return a + b
a = 1
b = 2
print('求和的结果为' + f'{sum_a_b(a,b)}')
#多行f
xname = 'barry'
age = 18
ajd = 'handsome'

# speaker = f'''Hi {name}.
# You are {age} years old.
# You are a {ajd} guy!'''

speaker = f'Hi {name}.'\
          f'You are {age} years old.'\
          f'You are a {ajd} guy!'
print(speaker)
#其他
print(f"{{73}}")  # {73}
print(f"{{{73}}}")  # {73}
print(f"{{{{73}}}}")  # {{73}}
m = 21
# ! , : { } ;这些标点不能出现在{} 这里面。
# print(f'{;12}')  # 报错
# 所以使用lambda 表达式会出现一些问题。
# 解决方式:可将lambda嵌套在圆括号里面解决此问题。
x = 5
print(f'{(lambda x: x*2) (x)}')  # 10

Iterator

In python, whenever an object contained inside iter methods are iterable .

By dir () to judge what object has a method

dir()会返回一个列表,这个列表中含有该对象的以字符串的形式所有方法名。
s1 = 'alex'
print(dir(s1))

s1 = 'alex'
i = 100
print('__iter__' in dir(i))  # False
print('__iter__' in dir(s1))  # True

从字面意思来说:可迭代对象就是一个可以重复取值的实实在在的东西。

​ 从专业角度来说:但凡内部含有__iter__方法的对象,都是可迭代对象。

​ 可迭代对象可以通过判断该对象是否有__iter__方法来判断。

​ 可迭代对象的优点:

​ 可以直观的查看里面的数据。

​ 可迭代对象的缺点:

​ 1.占用内存。

​ 2.可迭代对象不能迭代取值(除去索引,key以外)。

In python, and internal containing __Iter__ method objects with the method __next__ iterators.

o1 = 'alex'
o2 = [1, 2, 3]
o3 = (1, 2, 3)
o4 = {'name': '太白','age': 18}
o5 = {1, 2, 3}
f = open('file',encoding='utf-8', mode='w')
print('__iter__' in dir(o1))  # True
print('__iter__' in dir(o2))  # True
print('__iter__' in dir(o3))  # True
print('__iter__' in dir(o4))  # True
print('__iter__' in dir(o5))  # True
print('__iter__' in dir(f))  # True

print('__next__' in dir(o1))  # False
print('__next__' in dir(o2))  # False
print('__next__' in dir(o3))  # False
print('__next__' in dir(o4))  # False
print('__next__' in dir(o5))  # False
print('__next__' in dir(f))  # True
f.close()
只有文件句柄是迭代器,剩下的那些数据类型都是可迭代对象。

Iterative how objects can be converted into an iterator:

l1 = [1, 2, 3, 4, 5, 6]
obj = l1.__iter__()
# <list_iterator object at 0x000002057FE1A3C8>
# 或
obj = iter(l1)
print(obj)
# <list_iterator object at 0x102cc67f0

Iterator values:

Iterables been iterative value is not (removal index, slicing and Key), but can be converted to the iterator, using the value of the iterator is __next __ ():

l1 = [1, 2, 3,]
obj = l1.__iter__()  # 或者 iter(l1)
# print(obj)  # <list_iterator object at 0x000002057FE1A3C8>
ret = obj.__next__()
print(ret)
ret = obj.__next__()
print(ret)
ret = obj.__next__()
print(ret)
ret = obj.__next__()  # StopIteration
print(ret)
# 迭代器利用next取值:一个next取对应的一个值,如果迭代器里面的值取完了,还要next,
# 那么就报StopIteration的错误。

Literally speaking: iterator that can iterate the value of the tool.

From a professional standpoint: in python, and internal containing __Iter__ method objects with the method __next__ iterators.

Advantage of iterators: to save memory. Iterator equivalent to only one data space in memory: because both the value of each piece of data in memory will be released this entry load current data.

Inert mechanism. next time, take a value, not too much value.

Iterator has a good pattern can explain the two above: iteration is the cornerstone of data processing. When scan data set does not fit in memory, to find a way to obtain a data item inert, i.e. demand fetch one data item. This is an iterative mode.

Shortcoming iterator: not intuitive view of data inside.

When the value is not turning back, only has value down.

l1 = [1, 2, 3, 4, 5, 6]
obj = iter(l1)

for i in range(2):
    print(next(obj))

for i in range(2):
    print(next(obj))

Iterables:

Is a proprietary method more flexible operation (such as a list, CRUD dictionaries, and the like commonly used method of operation of the string), more intuitive, but take up memory, and not directly by the loop iteration values ​​of such a data set .

Application : When you focus on flexibility for data processing, and sufficient memory space, the data set is set to iterables is the clear choice.

Iterator:

Is a very save memory, can record the position values, the values ​​may be directly through the loop + next method, but not intuitive method of operating a single set of data comparison.

Application : When your data is too large, large enough to explode your memory or your memory as to save the first factor, the data set is set iterator is a good choice

Guess you like

Origin www.cnblogs.com/sundawei7/p/11209786.html