前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 高级特性:List Comprehensions

python 高级特性:List Comprehensions

作者头像
py3study
发布2020-01-14 20:02:21
3740
发布2020-01-14 20:02:21
举报
文章被收录于专栏:python3

列表生成式: 创建List

格式:

        新列表 = [表达式/函数 for 变量 in 旧列表]

一、普通创建List

#!/usr/bin/python

#common establish way lis1 = []; for x in range(1, 10):     lis1.append(x); print "lis1:", lis1;

1.PNG
1.PNG

二、列表生成式

#List comprehensions lis2 = [x for x in range(1, 10)] print "lis2:", lis2;

2.PNG
2.PNG

#also can choose the even number in list lis3 = [x * x for x in range(1, 10) if x%2 == 0] print "lis3:", lis3;

3.PNG
3.PNG

#two for in list lis4 = [x + y for x in 'ABC' for y in 'XYZ'] print "lis4:", lis4;

4.PNG
4.PNG

#show the file in directory import os;     #导入OS模块 lis5 = [d for d in os.listdir('.')] print lis5;

5.PNG
5.PNG

#convert all big_write string to small_write L = ['ABC', 'EFG', 'Hij', '8']   #只能为char类型,其他类型提示出错 lis6 = [s.lower() for s in L]   #lower()是内置函数,将大写转为小写 print lis6;

6.PNG
6.PNG
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/06/28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档