python-list生成式
2019-06-15 10:43
141 查看
python-list生成式 简单的 a = list(range(1, 10)) range(10):生成一个0-9的可迭代的range对象 type(range(10)) 查看类型 list()函数将一个可迭代的对象转换成list对象 type(a) 查看 当需要使用for循环一定的次数 for i in range(10): xxx 高级的 使用for a = [x * x for x in range(1, 10)] print(a) [1, 4, 9, 16, 25, 36, 49, 64, 81] 加if判断 a = [x * x for x in range(1, 11) if x % 2 == 0] print(a) [4, 16, 36, 64, 100] 两层循环 a = [m + n for m in 'ABC' for n in 'XYZ'] print(a) ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ'] 列出当前目录下的所有文件和目录名 import os a = [d for d in os.listdir('.')] print(a) ['my.py', 'one.py', 'thr.py', 'two.py'] 对两个变量用for d = {'x': 'A', 'y': 'B', 'z': 'C' } a = [k + '=' + v for k, v in d.items()] print(a) ['x=A', 'y=B', 'z=C'] 把一个list中所有的字符串变成小写 L = ['Hello', 'World', 'IBM', 'Apple'] a = [s.lower() for s in L] print(a) ['hello', 'world', 'ibm', 'apple']
相关文章推荐
- 列表生成式 是Python内置的非常简单却强大的可以用来创建list的生成式。
- python 如何用列表生成式创建2维list?
- Python中list列表生成式如何操作使用?list详解
- python学习:list&tuple
- Python笔记-list、tuple、dict、set
- Python技巧——list与字符串互相转换
- Python学习笔记 —— List列表
- Python 列表(list)、字典(dict)、字符串(string)常用基本操作小结
- python--列表list()操作
- Python List数据的遍历
- Python 中list, dictionary 与 file相互操作
- python list去重保留原先的次序
- 今天的感悟,对于python中的list()与w3c教程
- python基本数据类型——list
- python中的list和tuple的用法和区别?
- Python中list、tuple、dict、set总结
- python3 对list中每个元素进行处理的方法
- Python入门(五):list、tuple和字符串切片
- python之列表(list)的使用方法介绍
- Python中List的去重问题