python 基础
Posted gugubeng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 基础相关的知识,希望对你有一定的参考价值。
列表推导式
概念:提供了一种创建列表的简单快速的途径
(1) 一般形式
myList = [x for x in range(10)]
?
#分解后
myList = []
for x in range(10):
myList.append(x)
print(myList)
(2) 一般形式+判断
myList = [x for x in range(1,21) if x>10]
myList = [x for x in range(1,21) if x%2==0 and x<10]
(3) 生成列表嵌套
#第三种 生成列表嵌套
myList = [[x,x+1,x+2] for x in range(10)]
print(myList)
(4) 循环嵌套
#第四种 循环嵌套
myList = [x for x in range(3) for y in range(10)]
myList = [[x,y] for x in range(3) for y in range(10)]
3*4矩阵列表
myList = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]
]
变成4*3矩阵列表
newList = [[v[i] for v in myList] for i in range(4)]
拆分
newList = []
for i in range(4):
appendList = []
for v in myList:
# print(v[i])
appendList.append(v[i])
newList.append(appendList)
print(newList)
(5) 字典推导式
Dict = {k:v for k,v in [(‘a‘,‘a‘),(‘b‘,‘b‘)]}
print(Dict)
以上是关于python 基础的主要内容,如果未能解决你的问题,请参考以下文章