Python迭代器与格式化

三元运算

对if…else判断的简写

>>> age = 18
>>> res = "You are so young!" if age < 18 else "You are so eld!"
### 如果满足条件就返回前面的内容,不满足就返回后面的内容
>>> print(res)
You are so eld!

正则表达式

>>> test_list = [1,2,3,4,5]
>>> result_list = [i*i for i in test_list] 
>>> print(result_list)
[1, 4, 9, 16, 25]

>>> result_list = [i**i for i in test_list if i < 3]  ##还可以为正则表达式添加一个判断条件
>>> print(result_list)
[1, 4]

迭代器和可迭代对象

迭代器对象要求支持迭代器协议的对象,在Python中,支持迭代器协议就是实现对象的__iter__()和next()方法。其中__iter__()方法返回迭代器对象本身;next()方法返回容器的下一个元素,在结尾时引发StopIteration异常

#############for循环的本质#############
>>> test_list = [1,2,3,4]
>>> iter_list = test_list.__iter__()   ##通过这种方法把iter_list变为迭代器
>>> print(type(iter_list))
<class 'list_iterator'>        
>>> print(iter_list.__next__())     ##用__next__()方法实现
1
>>> next(iter_list)           ##用next()方法实现
2
>>> next(iter_list)
3
>>> next(iter_list)
4
>>> next(iter_list)
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>   
    next(iter_list)
StopIteration   ##当遍历完之后就会报错

可迭代对象可以分为,

第一类是集合数据类型

第二类是generator,包括生成器和带yield的函数

生成器

在 Python 中,使用了 yield 的函数被称为生成器(generator)

>>> people = ("People_%s" %i for i in range(10))  ##写在()里的就叫做正则表达式
>>> next(people)
'People_0'
>>> next(people)
'People_1'
>>> next(people)
'People_2'
>>> next(people)
'People_3'
>>> next(people)
'People_4'
>>> next(people)
'People_5'
>>> next(people)
'People_6'
>>> next(people)
'People_7'
>>> next(people)
'People_8'
>>> next(people)
'People_9'
>>> next(people)
Traceback (most recent call last):
  File "<pyshell#48>", line 1, in <module>
    next(people)
StopIteration

格式化

%[(name)][flags][width].[precision]typecode方式
  • (name) 为命名
  • flags 可以有 +,-,' '或 0.+ 表示右对齐.- 表示左对齐。' ' 为一个空格,表示在正数的左侧填充一个空格,从而与负数对齐。0 表示使用 0 填充
  • width 表示显示宽度
  • precision 表示小数点后精度
常用类型码 作用
%s 字符串 (采用str()的显示)
%d 十进制整数
%i 十进制整数
%f 浮点数
%% 字符“%”
>>> print("%.2f" %2.13414)
2.13
>>> print("I like to %s" %"read")
I like to read
format(self, *args, **kwargs)
数字 格式 输出 描述
3.1415926 {:.2f} 3.14 保留小数点后两位
3.1415926 {:+.2f} +3.14 带符号保留小数点后两位
-1 {:+.2f} -1.00 带符号保留小数点后两位
2.71828 {:.0f} 3 不带小数
5 {:0>2d} 05 数字补零 (填充左边, 宽度为2)
5 {:x<4d} 5xxx 数字补x (填充右边, 宽度为4)
10 {:x<4d} 10xx 数字补x (填充右边, 宽度为4)
1000000 {:,} 1,000,000 以逗号分隔的数字格式
0.25 {:.2%} 25.00% 百分比格式
1000000000 {:.2e} 1.00e+09 指数记法
13 {:10d} 13 右对齐 (默认, 宽度为10)
13 {:<10d} 13 左对齐 (宽度为10)
13 {:^10d} 13 中间对齐 (宽度为10)
>>> print("I am {name} and {age} years old, from {hometown}".format(name = "Hermaeus", age = 19, hometown = "meishan"))
I am Hermaeus and 19 years old, from meishan

>>> print("I an {0} and {1} years old, from {2}".format( "Hermaeus",19, "meishan"))   
I an Hermaeus and 19 years old, from meishan

>>> print("I am {name}, {age} years old!".format(**{"name":"Hermaeus","age":19}))     
I am Hermaeus, 19 years old!

猜你喜欢

转载自www.cnblogs.com/MingleYuan/p/10628518.html