- 列表的复制
a = [1,2,3] b = a[:] print a print b
- 结果 [1, 2, 3]
[1, 2, 3] - 以下方法是错误的
a = [1,2,3] c = a c[2] = 6 print a print c
结果:[1, 2, 6] 这里c 只是a 的别名,改变c 的同时也改变了a
[1, 2, 6]
- 列表与元组区别
- 列表元素可修改,元组元素不可修改
-
a = [1,2,3] a[1] = 5 print a b=(1,5,7) b[1] = 3
- 结果
[1, 5, 3] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "D:\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 580, in runfile execfile(filename, namespace) File "C:/Users/jingling/Desktop/11.py", line 168, in <module> b[1] = 3 TypeError: 'tuple' object does not support item assignment
- 列表增加元素append , extend
a = [1,2,3] print a a.extend([7,8]) print a a.append([7,8]) print a
[1, 2, 3]
[1, 2, 3, 7, 8]
[1, 2, 3, 7, 8, [7, 8]]
- 列表解析
a = [1,2,3] print a d = [] for i in a: d.append(i+2) print d d = [i+2 for i in a] print d
- 结果[1, 2, 3]
[3, 4, 5]
[3, 4, 5]
- list ,tuple
- 将对象转换为列表和元组
f = 'ab' print(list(f)) print(tuple(f))
- ['a', 'b']
('a', 'b')
- 字典 dict
g = {'min': 20, 'Io': 30} print g print (dict([['you',20], ['he', 15]])) print (dict.fromkeys(['today','tomorrow'],15))
- 结果{'Io': 30, 'min': 20}
{'you': 20, 'he': 15}
{'tomorrow': 15, 'today': 15}
- 集合 set
s = {1, 2, 2, 3} # 注意2会自动删掉 print s t = set([4,2,6]) # 将列表转换为集合 print t a = s | t # s 和 t 的并集 b = s & t # s 和 t 的交集 c = s - t # 求差集 (项在 s 中, 不在 t 中) d = s ^ s # 对称差集 (项在 t 中或 s 中, 但不会同时出现在二者中) print a print b print c print d
- 结果
- set([1, 2, 3])
set([2, 4, 6])
set([1, 2, 3, 4, 6])
set([2])
set([1, 3])
set([])
- 编程常用函数 lambda, map, reduce, filter
- lambda 函数, map
- f = lambda x: x+2 # 定义函数 f(x) = x+2
- g = lambda x, y :x+y # 定义函数g(x, y) = x+y
a = [1, 2, 3] b = map(lambda x: x+2, a) # map函数将列表中的元素逐一应用到lambda print b
- 结果[3, 4, 5]
- reduce 函数
- reduce (lambda x,y:x*y, range(1,n+1))
- 其中reduce(x1,n+1) 相当于给出一个列表,元素是1~n这n个整数。 lambda 构造了一个二元函数,返回两个参数的成绩。 reduce 命令首先列表的前两个元素作为函数的参数进行运算,然后将运算的结果与第三个数字作为函数的参数............一次类推,知道列表列表结束,返回最终的结果。用循环命令,那就写成:
s = 1 for i in range(1, n+1): s = s * i
- filter 函数,用来筛选出列表中符合条件的元素,例如:
b = filter ( lambda x: x > 5 and x < 8, range(10)) print b
结果
[6, 7]- 使用filter函数首先需要一个返回值为bool型的函数,如上述的lambda x:x >5 and x <8 , d定义了一个函数,判断x 是否大于5且小于8,然后
python list,map,lambda, set,filter
最新推荐文章于 2022-11-18 15:53:30 发布