您的位置:首页 > 编程语言 > Python开发

python --- 元组与集合的基础知识

2017-09-05 22:48 477 查看
python — 元组与集合的基础知识

一、元组

特点:

1、有序的集合

2、通过偏移来取数据

>>>
>>> a = (1,2,3,4,5)
>>> a
(1, 2, 3, 4, 5)
>>> a[0]
1
>>> a[1:4]
(2, 3, 4)
>>> a[1:2]
(2,)
>>> a[1:1]
()
>>>
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
>>>
>>>
>>> b = list(a)#把元组a转换list(b)
>>> b
[1, 2, 3, 4, 5]
>>> b[0] = 9#修改List(b)的第一个元素的值
>>> b
[9, 2, 3, 4, 5]
>>> a
(1, 2, 3, 4, 5)
>>> type(b)
<type 'list'>
>>> type(a)
<type 'tuple'>
>>> a = tuple(b)#使用tuple把list(b)转换成新的一个元组对象
>>> a#元组a的值更新
(9, 2, 3, 4, 5)
>>> b
[9, 2, 3, 4, 5]
>>> type(b)
<type 'list'>
>>> type(a)
<type 'tuple'>
>>>


3、属于不可变的对象,不能在原地修改内容,没有排序,修改等操作。

那为什么有序列表还要有元组呢

元组不可变的好处:保证数据的安全,比如我们传给一个不熟悉的方法。确保不会改变我们的数据从而导致程序的问题。

def info(a):

””一个我们不熟悉的方法”’

a[0] = ‘haha’

a = [1,2,3]

info(a)

print a

tuple类型转换

元组例子如下:

root@kali:~/python/laowangpy# vi test_def_info.py
root@kali:~/python/laowangpy# python test_def_info.py
start-
3075163276
id 3075163276
['haha', 2, 3]
root@kali:~/python/laowangpy# cat test_def_info.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--

def info(a):
print 'id %d' %id(a)
a[0] = 'haha'

a = [1,2,3]
print 'start-'
print id(a)

info(a)

print a
root@kali:~/python/laowangpy#
root@kali:~/python/laowangpy#
root@kali:~/python/laowangpy# vi test_def_info.py
root@kali:~/python/laowangpy# cat test_def_info.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--

def info(a):
print 'id %d' %id(a)
a[0] = 'haha'
return a

a = [1,2,3]
print 'start-'
print id(a)

info(a)

print a
root@kali:~/python/laowangpy# python test_def_info.py
start-
3074585740
id 3074585740
['haha', 2, 3]
root@kali:~/python/laowangpy#


列表例子如下:

root@kali:~/python/laowangpy# vi test_def_info_list.py
root@kali:~/python/laowangpy#
root@kali:~/python/laowangpy# cat test_def_info_list.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--

def info(a):
b = a [:]#新建新的列表对象
b[0] = 'haha'#新的列表对象第一个值赋值
return a#返回a的原始列表

a = [1,2,3]
print 'start-'
print id(a)

info(a)

print a
root@kali:~/python/laowangpy# python test_def_info_list.py
start-
3075216524
[1, 2, 3]
root@kali:~/python/laowangpy#


二、集合:集合是没有顺序的概念。所以不能用切片和索引操作。

1、创建集合。set():可变的 frozenset():不可变的

set()方法接收的参数为可迭代对象,如列表、字典、字符串。而数字是不可迭代的对象。查询是否为可迭代对象,主要看dir()里面有没有内置的一个方法为iter

root@kali:~/python/laowangpy# python
Python 2.7.3 (default, Mar 14 2014, 11:57:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = []
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>>
>>> a =(12,23)
>>> dir (a)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
>>>
>>> dir(4)#数字就没有内置方法__iter__,所有不是可迭代的对象
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
>>>
>>>
>>> b = set('abc')#创建可变集合操作
>>> b
set(['a', 'c', 'b'])
>>>
>>> a = frozenset('abcd')#不可变的对象
>>> a
frozenset(['a', 'c', 'b', 'd'])
>>> a.add('233')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
>>> a.remove('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'remove'
>>> a.append('1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'append'
>>>


2、添加操作:add,update

>>>
>>> b = set('abc')
>>> b
set(['a', 'c', 'b'])
>>>
>>> b.add('python')#add是作为一个整体插入
>>> b
set(['a', 'python', 'c', 'b'])
>>> b.update('java')#update是作为每个元素进行插入,重复元素就不插入
>>> b
set(['a', 'c', 'b', 'python', 'j', 'v'])
>>>


3、删除 remove

>>>
>>> b.remove('python')
>>> b
set(['a', 'c', 'b', 'j', 'v'])
>>> b.remove('a')
>>> b
set(['c', 'b', 'j', 'v'])
>>> b.remove('x')#不存在元素
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'x'
>>> b
set(['c', 'b', 'j', 'v'])
>>>


4、成员关系 in,not in

>>>
>>> 'c' in b
True
>>> 'r' in b
False
>>>
>>> 'python' in b
False
>>> 'python'  not in b
True
>>>


5、交集、并集、差集 & | -

>>> a = set('efg')
>>> b = set('cdef')
>>> a & b#共同拥有的元素
set(['e', 'f'])
>>> a | b
set(['c', 'e', 'd', 'g', 'f'])
>>> a - b#列表b中没有的元素
set(['g'])
>>> b - a#列表a中没有的元素
set(['c', 'd'])
>>>


6、set 去重 列表内容元素重复

>>>
>>> a = [1,2,3,45]#创建列表
>>> a
[1, 2, 3, 45]
>>> a.append(1)
>>> a.append(3)
>>> a
[1, 2, 3, 45, 1, 3]
>>> set(a)#把列表a变成集合
set([1, 2, 3, 45])
>>> a
[1, 2, 3, 45, 1, 3]
>>> list(set(a))#把集合a变成list显示
[1, 2, 3, 45]
>>> a
[1, 2, 3, 45, 1, 3]
>>>


#encoding=utf-8
##可变集合
info = set('abc')
info.add('python')#添加单个对象到集合里
print info
info.remove('python')
print info
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 元组 集合