zip函数
在学习pyecharts可视化工具时,里面有一句代码:
[list(z) for z in zip(Faker.choose(), Faker.values())]
有些忘记;先重新复习。
zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c) # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped) # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]
参考:
Python zip() 函数
f_string(f字符串)格式化字符串
从python 3.6开始
旧时代的格式化字符串
%-formatting
引入时间
OG(original generation);
使用
# 单个变量
name = "Eric"
"Hello, %s." % name
## 多个变量
name = "Eric"
age = 74
"Hello, %s. You are %s." % (name, age)
局限
开始使用几个参数和更长的字符串,代码将很快变得不太容易阅读。事情已经开始显得有点凌乱:
first_name = "Eric"
last_name = "Idle"
age = 74
profession = "comedian"
affiliation = "Monty Python"
"Hello, %s %s. You are %s. You are a %s. You were a member of %s." %\
(first_name, last_name, age, profession, affiliation)
str.format()
引入时间
python 2.6;是对%.formating的改进
使用
# 常规
"Hello, {}. You are {}.".format(name, age)
# 通过索引
"Hello, {1}. You are {0}-{0}.".format(age, name)
# 地址信息1
person = {'name': 'Eric', 'age': 74}
"Hello, {name}. You are {age}.".format(name=person['name'], age=person['age'])
# 地址信息2 利用**
"Hello, {name}. You are {age}.".format(**person)
局限
使用str.format()的代码比使用%-formatting的代码更易读,但当处理多个参数和更长的字符串时,str.format()仍然可能非常冗长。
f-Strings
引入时间
python 3.6
使用
name = "Eric"
age = 74
# 格式1
f"Hello, {name}. You are {age}."
# 格式2
F"Hello, {name}. You are {age}."
由于f字符串是在运行时进行渲染的,因此可以将任何有效的Python表达式放入其中。
# 运算
f"{2 * 37}"
# 调用函数
f"{name.lower()} is funny."
本部分参考python3 f-string格式化字符串的高级用法,其他用法也请参考该文章。
数字格式化
f-String也可以用下述格式的。
data = f"{3.25222:.2f}"
输出为:3.25
参考Python format 格式化函数