python数据结构共包含四大类:
列表是可变元素,支持增删改查操作
字典是遍历,key:value 格式.
元组数据不可变元素,仅仅有两个操作 index, count
集合的增删,创建集合{1, 2, 3}, set(),集合的集合操作.
列表解析是python重要的语法糖,速度比for in迭代快,推荐使用
ret = [expression for item in iterator]
等价于:
ret = []
for item in iterator:
ret.append(expression)
实例:
# 列表解析形式 In [1]: lst = list(range(1,11)) In [2]: lst Out[2]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] In [3]: [x ** 2 for x in lst] Out[3]: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] # for循环方式 In [6]: lst Out[6]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] In [7]: ret=[] In [8]: for i in lst: ...: ret.append(i ** 2) In [10]: print(ret) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In [32]: [(x, y) for x in list1 for y in listb] Out[32]: [(1, ‘a‘), (1, ‘b‘), (1, ‘c‘), (2, ‘a‘), (2, ‘b‘), (2, ‘c‘), (3, ‘a‘), (3, ‘b‘), (3, ‘c‘)]
基本语法:
ret = [expression for item in iterator if X if Y]
等同于
ret = [] for item in iterator: if X and Y: ret.append(expression)
实例:
In [34]: list1 = [2, 3, 4, 5, 6, 7] In [35]: [x ** 2 for x in list1 if x<6 ] Out[35]: [4, 9, 16, 25]
ret = {exprK:exprV for item in iterator}
等同于
ret = dict() for item in iterator: ret.update({exprK: exprV})
字典解析实例:
生成字典的方式:
In [26]: lista Out[26]: [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘] In [27]: listb Out[27]: [1, 2, 3, 4, 5] In [28]: {k:v for k in lista for v in listb} Out[28]: {‘a‘: 5, ‘b‘: 5, ‘c‘: 5, ‘d‘: 5, ‘e‘: 5} In [29]: {k:v for k, v in [(‘a‘, 1), (‘b‘, 2)]} Out[29]: {‘a‘: 1, ‘b‘: 2}
# 生成集合 In [36]: {x + 1 for x in range(10)} Out[36]: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} #集合解析 In [38]: {x+1 for x in [2, 2, 2, 3]} Out[38]: {3, 4}
原文:http://www.cnblogs.com/topicjie/p/5223725.html