博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
day10-列表生成式
阅读量:4641 次
发布时间:2019-06-09

本文共 2856 字,大约阅读时间需要 9 分钟。

列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。

1、生成一个列表

a = [i for i in range(1,100) if i%2==1]

print(list(a))或print(a)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]

或一句话输出

print([i for i in range(1,100) if i%2==0])
[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]

2、生成[1x1, 2x2, 3x3, ..., 10x10]

方法一是循环

L = []
for x in range(1, 11):
L.append(x * x)
print(L)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

方法二用一行语句代替循环生成list

print([x * x for x in range(1, 11)])
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
写列表生成式时,把要生成的元素x * x放到前面,后面跟for循环,就可以把list创建出来。

3、for循环后面还可以加上if判断,可以筛选出仅偶数的平方

print([x * x for x in range(1, 11) if x % 2 == 0])
[4, 16, 36, 64, 100]

也可以用filter()和lambda实现上面的功能:

print(list(filter(lambda x:x%2==0,range(10))))
[0, 2, 4, 6, 8]

filter():filter(function,list),把list中的元素一个个丢到function中,Return True的元素组成一个new list。

lambda匿名函数,lambda a:b,其中a表示参数,b表示返回值。

总结:

1、循环list的时候,最好用for i in list:,减少因为del()犯下不易察觉的失误。
2、在python2 中直接打印map,filter函数会直接输出结果。但在python3中做了些修改,输出前需要使用list()进行显示转换。

 

对 numbers 的每个数求平方

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print([x * x for x in numbers])
[1, 4, 9, 16, 25, 36, 47, 84, 81, 100]

还可以使用两层循环,可以生成全排列:

print([m + n for m in 'ABC' for n in 'XYZ'])
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

4、列出当前目录下的所有文件和目录名

import os # 导入os模块,模块的概念后面讲到
print([d for d in os.listdir('.')]) # os.listdir可以列出文件和目录
['.emacs.d', '.ssh', '.Trash', 'Adlm', 'Applications', 'Desktop', 'Documents', 'Downloads', 'Library', 'Movies', 'Music', 'Pictures', 'Public', 'VirtualBox VMs', 'Workspace', 'XCode']

5、使用两个变量来生成list,类似于通过for循环迭代dict的items()取出key和value

d = {'x': 'A', 'y': 'B', 'z': 'C' }

print([k + '=' + v for k, v in d.items()])
['y=B', 'x=A', 'z=C']

6、把一个list中所有的字符串变成小写

L = ['Hello', 'World', 'IBM', 'Apple']
print([s.lower() for s in L])
['hello', 'world', 'ibm', 'apple']

如果list中既包含字符串,又包含整数,由于非字符串类型没有lower()方法,所以列表生成式会报错:

L = ['Hello', 'World', 18, 'Apple', None]
print([i.lower() for i in L])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
AttributeError: 'int' object has no attribute 'lower'

使用内建的isinstance函数可以判断一个变量是不是字符串:

>>> x = 'abc'
>>> y = 123
>>> isinstance(x, str)
True
>>> isinstance(y, str)
False

通过添加if语句保证列表生成式能正确地执行:

[i.lower() for i in L if isinstance(i,str)]
['hello', 'world', 'apple']

或者用type()判断也可以,推荐用isinstance()

print([i.lower() for i in L if type(i)==str])

7、设置range中的步长

a = range(1,10)
print(list(a))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

b = range(1,10,2)

print(list(b))
[1, 3, 5, 7, 9]

 

转载于:https://www.cnblogs.com/dxnui119/p/9829836.html

你可能感兴趣的文章
第十七章 springboot + devtools(热部署)
查看>>
MyBatis Spring MapperScannerConfigurer 配置
查看>>
学习v-on的使用
查看>>
Arduino下读取DHT22温湿度(不使用第三方库)
查看>>
最长不重复子串
查看>>
asp.net 逻辑操作符与(&&),或(||),非(!)
查看>>
Linux的进程/线程通信方式总结(转)
查看>>
一个java程序员的C++学习之路(整理)
查看>>
10个出色的NoSQL数据库
查看>>
枚举类Enum
查看>>
黑科技项目:英雄无敌III Mod <<Fallen Angel>>介绍
查看>>
UESTC - 1652 递推方程
查看>>
Codeforces - tag::dp 大合集 [占坑 6 / inf]
查看>>
判断整除
查看>>
[saiku] 登陆/选择cube 时发生了什么
查看>>
iOS 知识点
查看>>
redis引发的一系列生产问题
查看>>
ubuntu16.04 自建源
查看>>
C#基础知识
查看>>
Javascript之DOM的三大节点及部分用法
查看>>