20180112-python学习笔记-列表生成式

本文介绍Python列表生成式的使用方法,包括基本语法、条件筛选及复杂应用实例,如目录读取、字符串转换等。

备注:

#列表生成式

#要生成list [1x1, 2x2, 3x3, ..., 10x10]

L = []
for i in range(1, 11):
    i = i * i
    L.append(i)

print (L)


#用列表生成式来完成这个任务
[x * x for x in range(1, 11)]


#要生成的元素x * x放到前面,后面跟for循环,就可以把list创建出来
[x * x * x for x in range(1, 100)]
#[4, 16, 36, 64, 100]

#偶数的三次方
[x * x * x for x in range(1, 100) if x % 2 ==0]

[x * x for x in range(1, 11) if x % 2 ==0]

#全排列
[m + n for m in 'xyz' for n in 'abc']
#['xa', 'xb', 'xc', 'ya', 'yb', 'yc', 'za', 'zb', 'zc']


#列表生成式展示文件目录
import os #首先导入os包
[d for d in os.listdir('C://Program Files')] # 里面放入C盘目录
#选取大家C 盘 的文件安装目录


#之前迭代 循环dict 里面的key  value 也可以用列表表达式完成
d = {'x': 'A', 'y': 'B', 'z': 'C' }
[k + ':' + v for k, v in d.items()]

#['x:A', 'y:B', 'z:C']


#把一个list中所有的字符串变成小写
L = ['Hello', 'World', 'IBM', 'Apple']
[x.lower() for x in L]
#['hello', 'world', 'ibm', 'apple']



'''
练习
如果list中既包含字符串,又包含整数,由于非字符串类型没有lower()方法,所以列表生成式会报错:
>>> L = ['Hello', 'World', 18, 'Apple', None]
>>> [s.lower() for s 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)
111/531
False
请修改列表生成式,通过添加if语句保证列表生成式能正确地执行:
# -*- coding: utf-8 -*-
L1 = ['Hello', 'World', 18, 'Apple', None]
----
L2 = ???
----
# 期待输出: ['hello', 'world', 'apple']
print(L2)
'''

L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [s.lower() for s in L1 if isinstance(s, str)]
print (L2)

 

posted on 2018-01-12 15:40 liyihao 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/liyihao/p/8276092.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值