今天我们使用Python中的列表解析式来实现一些简单功能。好了关于列表解析式是什么?我的理解是它可以根据已有列表,高效创建新列表的方式。列表解析是Python迭代机制的一种应用,它常用于实现创建新的列表,返回的是一个列表,因此用在[]中。好了,下面我们通过一些实际的例子来看一下列表解析式的使用:
生成1*1,2*2,3*3,4*4,5*5,6*6,9*9的序列
使用for循环的实现方法:
a = []
for i in range(1,11):
a.append(i*i)
print (a)
输出结果如下:
C:\Python34\python3.exe E:/Project_case/demo.py
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
使用列表解析式生成1*1,2*2,3*3,4*4........9*9的序列
a1 = [x*x for x in range(1,11)]
print (a1)
输出结果:
C:\Python34\python3.exe E:/Project_case/demo.py
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
生成1-100以内的偶数
a2 = []
for i in range(1,101):
if i %2==0:
a2.append(i)
else:
pass
print(a2)
输出结果:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]
使用列表解析式:
a3 = [x for x in range(1,101) if x % 2==0]
print (a3)
输出结果:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]
使用两层循环生成全排列
a4 = [m+n for m in 'ABCD' for n in 'abcd']
print(a4)
输出结果:
['Aa', 'Ab', 'Ac', 'Ad', 'Ba', 'Bb', 'Bc', 'Bd', 'Ca', 'Cb', 'Cc', 'Cd', 'Da', 'Db', 'Dc', 'Dd']
使用变量生成List
#字典实现方法items
demo = {'A':'a','B':'b','C':'c','D':'d'}
for k,v in demo.items():
print(k,'====',v)
转换列表解析式:
demo = {'A':'a','B':'b','C':'c','D':'d'}
a5 = [k + '===' + v for k,v in demo.items()]
print(a5)
输出结果:
C:\Python34\python3.exe E:/Project_case/demo.py
['A===a', 'B===b', 'D===d', 'C===c'] 进程已结束,退出代码0
将LIST中大写变成小写
a = ['Python','Java','PHP','Javascript','Monkey']
a6 = [x.lower() for x in a]
print(a6)
输出结果:
C:\Python34\python3.exe E:/Project_case/demo.py
['python', 'java', 'php', 'javascript', 'monkey']
列出当前目录下所有文件和目录
import os #导入模块
demo = [x for x in os.listdir('.')]
print(demo[-1]) #列出最后一个文件夹名
输出结果:
C:\Python34\python3.exe E:/Project_case/demo.py
WordPress_POM
列出当前文件夹下面的py文件
import os
d = [x for x in os.listdir('.') if x.endswith('.py')]
print(d)
输出结果:
C:\Python34\python3.exe E:/Project_case/demo.py
['cjol.py', 'demo.py']