集合与列表
集合操作符和关系符号
问题:
a = [1,3,5,7,9]
b = [‘a’,’c’,9,’d’]
1) 求出这两个列表中的共同元素
2) 列表的元素总和
3) 在a列表中不在b列表中的元素
a = [1,3,5,7,9]
b = ['a','c',9,'d']
set(a) & set(b)
set([9])
set(a) | set(b)
set(['a', 1, 'c', 3, 5, 7, 9, 'd'])
set(a) - set(b)
set([1, 3, 5, 7])
set(b) - set(a)
set(['a', 'c', 'd'])
集合本身也是一种序列,列表:有序 字典:无序 元祖:不可变 集合:不重复
元组
判断是否是元组,通过逗号“,”去识别,而不是括号“()”
a = 1,2
a
(1, 2)
type(a)
<type 'tuple'>
a = (2,3,5,7)
type(a)
<type 'tuple'>
a = 1,
type(a)
<type 'tuple'>
元组的值不可变
a = (2,3,5,7)
a[1]
3
a[1] = 9
Traceback (most recent call last):
Python Shell, prompt 203, line 1
TypeError: 'tuple' object does not support item assignment