列表推导式
列表推导式提供了从列表、元组创建列表的简单途径。语法:
创建并返回一个列表。if语句可选。
示例:
list1=[1,2,3,4] #使用元组也行
list2=[x*2 for x in list1]
print(list2) #[2, 4, 6, 8]
list3=[x*2+1 for x in list1]
print(list3) #[3, 5, 7, 9]
list1=[1,2,3,4]
list2=[x*2 for x in list1 if x>2] #if限定范围
print(list2) #[6, 8]
list1=[1,3,5,7] #使用元组也行,得到的仍然是列表
list2=[2,4,6,8]
list2=[x*y for x in list1 for y in list2 ] #可使用多个for语句
print(list2) #[2, 4, 6, 8, 6, 12, 18, 24, 10, 20, 30, 40, 14, 28, 42, 56]
矩阵
矩阵可使用列表\元组的嵌套来实现。
matrix=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]] #一个3*4的矩阵
"""
1 2 3
4 5 6
7 8 9
10 11 12
"""
del matrix[0][0] #删除第一行的第一个元素
print(matrix) #[[2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
del matrix[0] #删除第一行
print(matrix) #[[4, 5, 6], [7, 8, 9], [10, 11, 12]]
matrix.clear() #清空矩阵
print(matrix) #[]
del matrix #删除整个矩阵
#可使用循环来遍历矩阵
格式化输出
1、常用的输出方式
print("Download the file",end=" done\n") # Unpack the file done
"""
以指定值结尾,缺省end时默认为\n,所以缺省end时会自动换行。
"""
print("*"*50) #分隔线效果
list=["Download the file","Unpack the file","Open the file"]
for x in list:
print(x, end = " done\n")
"""
Download the file done
Unpack the file done
Open the file done
"""
2、转换为字符串
str1=str(1) #转换为字符串
print(type(str1)) #<class 'str'>
a=10
str2=str(a) #转换为字符串,a本身不变
print(str2) #10
print(type(str2)) #<class 'str'>
print(type(a)) #<class 'int'>
3、对齐方式
str="hello"
print(str.ljust(20," ")) #左对齐,不足20个字符右边填充空格(凑足20个字符)
print(str.rjust(20," ")) #右对齐,不足20个字符时,左边填充空格
print(str.center(20," ")) #居中对齐,不足20个字符时,两端填充空格
4、格式化输出
旧版本的格式化输出:
name="张三"
age=12
score=99
print("%s今年%d岁,成绩%.1f分"%(name,age,score)) #张三今年12岁,成绩99.0分
"""
print("格式串"%(对应的值))
有多个值时,值要放在()中。如果只有一个值,可以缺省():
print("我是%s"%name)
"""
新版本的格式化输出:
name="张三"
age=12
score=99
print("我是{0},今年{1}岁,成绩{2}分".format(name,age,score)) #我是张三,今年12岁,成绩99分
print("我是{},今年{}岁,成绩{}分".format(name,age,score)) #我是张三,今年12岁,成绩99分 {index}中的index可以缺省,缺省时默认依次为0,1,2,3....
print("我是{0},今年{1}岁,成绩{2:.1f}分".format(name,age,score)) #我是张三,今年12岁,成绩99.0分 可以指定具体格式
print("我是{},今年{}岁,成绩{:.1f}分".format(name,age,score)) #我是张三,今年12岁,成绩99.0分