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

python基础学习-集合数据类型

2017-08-17 13:45 405 查看
python语言本身提供除有基本数据类型外,还有相应的简单集合数据类型,常用的有列表,元组,集合,字典。当然也可以通过模块使用第三方的数据结构,比如说有矩阵,树,队列,堆栈,图等等。

其中列表是一种动态数据结构,在数据结构中体现为线性表或者链表。其中的动态这个词很重要,像元组和基本数据类型就是非动态的,因为在对待按值传递和按引用传递方面是如果是动态的就按引用传递,如果是非动态的就按值传递。当然,如果想动态也按值传递和话可以利用python的深copy特性。关于python的按值传递和按引用传递,在我的另一篇文章 


python基础学习-按值传递和按引用传递 中有相关的说明和解释,建议好好看看,这个真的超级重要。


python列表操作


Python 2.7.13 (default, Jan 19 2017, 14:48:08) 

[GCC 6.3.0 20170118] on linux2

Type "copyright", "credits" or "license()" for more information.

>>> numbers = [1,2,3,4,5,"6",[5,4,3,2,1]]#创建一个列表,其中包含了5个int和一个字符串以及另一个列表

>>> numbers

[1, 2, 3, 4, 5, '6', [5, 4, 3, 2, 1]]

>>> numbers.append(7)

>>> #python的列表中的元素是可以为任意类型的,并且同一个列表中的元素可以是不同类型的

>>> #向列表的末尾添加一个元素

>>> numbers

[1, 2, 3, 4, 5, '6', [5, 4, 3, 2, 1], 7]

>>> numbers.insert(0,0)

>>> #在特定位置插入一个元素

>>> numbers

[0, 1, 2, 3, 4, 5, '6', [5, 4, 3, 2, 1], 7]

>>> numbers[7] = 8

>>> #修改某个位置上的元素

>>> numbers

[0, 1, 2, 3, 4, 5, '6', 8, 7]


>>> numbers.insert(0,0)

>>> numbers

[0, 0, 1, 2, 3, 4, 5, '6', 8, 7]

>>> numbers.remove(0)#移除第一个匹配的元素

>>> numbers

[0, 1, 2, 3, 4, 5, '6', 8, 7]


>>> nums0 = [1,2,3]

>>> nums1 = [4,5,6]

>>> #两个列表连接起来

>>> nums2 = num0+num1

Traceback (most recent call last):

  File "<pyshell#20>", line 1, in <module>

    nums2 = num0+num1

NameError: name 'num0' is not defined

>>> nums = nums0+nums1

>>> nums

[1, 2, 3, 4, 5, 6]




python的列表和for循环的高级应用


>>> nums = [1,2,3,4,5]

>>> def test(i):
return i+1

>>> anotherNums = [test(item) for item in nums]

>>> anotherNums

[2, 3, 4, 5, 6]

>>> 






元组是个神奇的东西


两种创建元组的方式


>>> t = 1,2,3

>>> t

(1, 2, 3)

>>> t = (1,2,3)

>>> t

(1, 2, 3)

>>> 




元组解包


>>> a,b,c = t

>>> a

1

>>> b

2

>>> c

3




>>> (a,b,c) = t

>>> a

1

>>> b

2

>>> c

3



集合操作

>>> s1 = {1,2,3}

>>> s2 = {2,3,4}

>>> #集合并集

>>> s1 | s2

set([1, 2, 3, 4])

>>> #集合交集

>>> s1 & s2

set([2, 3])

>>> #集合差集

>>> s1 - s2

set([1])

>>> #集合对称差集

>>> s1 ^ s2

set([1, 4])

>>> #集合添加

>>> s1.add(5)

>>> s1

set([1, 2, 3, 5])

>>> s1.update({6,7,8})

>>> s1

set([1, 2, 3, 5, 6, 7, 8])

>>> #集合移除

>>> s1.remove(1)

>>> s1

set([2, 3, 5, 6, 7, 8])

python中的字典其实就是其他语言中的表

>>> dic = {1:1,2:2,3:3}

>>> dic

{1: 1, 2: 2, 3: 3}

>>> dic[1]

1

>>> for (a,b) in dic.items():
print a,",",b

1 , 1

2 , 2

3 , 3

>>> dic[1] = 100

>>> dic

{1: 100, 2: 2, 3: 3}

>>> del dic[1]

>>> dic

{2: 2, 3: 3}

字典的基本操作比较简单















































内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐