Python 列表、元组、字典及集合操作详解

一、列表

  • 列表是Python中最基本的数据结构,是最常用的Python数据类型,列表的数据项不需要具有相同的类型
  • 列表是一种有序的集合,可以随时添加和删除其中的元素
  • 列表的索引从0开始

1、创建列表

>>> list1 = ['python', 2018, 'python3', 1994]
>>> list1
['python', 2018, 'python3', 1994]

>>> list2 = [1, 2, 3, 4]
>>> list2
[1, 2, 3, 4]

>>> list3 = ['a', 'b', 'c', 'd']
>>> list3
['a', 'b', 'c', 'd']

2、获取列表元素个数

>>> len(list1)
4

3、访问列表中的值

(1)使用索引来访问列表中的值,列表的索引从0开始:

>>> list1[0]
'python'
>>> list1[1]
2018
>>> list1[2]
'python3'
>>> list1[3]
1994
>>> list1[4]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
IndexError: list index out of range

注意:当索引超出范围时,Python会报一个IndexError错误,所以,要确保索引不要越界,记得最后一个元素的索引是len(list1) - 1。

(2)还可以获取列表最后一个元素:

>>> list1[-1]
1994

以此类推,可以获取倒数第2个、倒数第3个、倒数第4个:

>>> list1[-2]
'python3'
>>> list1[-3]
2018
>>> list1[-4]
'python'
>>> list1[-5]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
IndexError: list index out of range

当然,倒数第5个元素已越界,需要注意一下。

(3)切片

截取列表前3个元素:

>>> list1[0:3]
['python', 2018, 'python3']

>>> list1[:3]   #如果第一个索引是0,可以省略
['python', 2018, 'python3']

倒数切片:

>>> list1[-2:]  #获取后2个元素
['python3', 1994]

>>> list1[-2:-1]
['python3']

前4个元素,每两个取一个:

>>> list1[:4:2]
['python', 'python3']

所有元素,每3个取一个:

>>> list1[::3]
['python', 1994]

原样复制一个列表:

>>> list1[:]
['python', 2018, 'python3', 1994]

4、合并列表

>>> list4 = list2 + list3
>>> list4
[1, 2, 3, 4, 'a', 'b', 'c', 'd']

5、更新列表

>>> list1
['python', 2018, 'python3', 1994]
>>> list1[1] = 2017
>>> list1
['python', 2017, 'python3', 1994]

6、删除列表

>>> del(list4)

7、清空列表

>>> list1
['python', 2017, 'python3', 1994]
>>> list1.clear()
>>> list1
[]

8、列表操作的函数和方法

列表操作包含以下函数:

cmp(list1, list2)  #比较两个列表的元素 
len(list)         #列表元素个数 
max(list)       #返回列表元素最大值 
min(list)      #返回列表元素最小值 
list(seq)     #将元组转换为列表     

列表操作包含以下方法:

list.append(obj)       #在列表末尾添加新的对象
list.count(obj)      #统计某个元素在列表中出现的次数
list.extend(seq)      #在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
list.index(obj)      #从列表中找出某个值第一个匹配项的索引位置
list.insert(index, obj) #将对象插入列表
list.pop(obj=list[-1]) #移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
list.remove(obj)     #移除列表中某个值的第一个匹配项
list.reverse()      #反向列表中元素
list.sort([func])    #对原列表进行排序

二、元组

元组(tuple)和列表(list)非常类似,但是元组一旦初始化就不能修改,且元组使用小括号而列表使用中括号。

1、创建元组

>>> tup1 = ('python', 2018, 'python3', 1994)
>>> tup1
('python', 2018, 'python3', 1994)

>>> tup2 = (1, 2, 3, 4)
>>> tup2
(1, 2, 3, 4)

>>> tup3 = ('a', 'b', 'c', 'd')
>>> tup3
('a', 'b', 'c', 'd')

注意:元组中只包含一个元素时,需要在元素后面添加逗号来消除歧义

>>> tup4 = ('hello',)

2、合并元组

>>> tup5 = tup2 + tup3
>>> tup5
(1, 2, 3, 4, 'a', 'b', 'c', 'd')

3、删除元组

>>> del(tup5)
>>> tup5 #此时tup5已不存在,所有报错
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'tup5' is not defined

元组的操作基本与列表的操作一直,除了不能修改元组本身外。

三、字典

  • 字典是另一种可变容器模型,且可存储任意类型对象,如字符串、数字、元组等其他容器模型
  • 字典在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度
  • 字典中键是唯一的,如果重复最后的一个键值对会替换前面的,值不需要唯一

1、创建字典

>>> dict1 = {'a': 1, 'b': 2, 'b': '3'}
>>> dict1
{'a': 1, 'b': '3'}  #因为键存在相同,所以后面的键值替换了前面的键值

>>> dict2 = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
>>> dict2
{'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

>>> dict3 = { 'abc': 123, 98.6: 37 }
>>> dict3
{'abc': 123, 98.6: 37}

2、访问字典中的值

>>> dict2['Beth']
'9102'

>>> dict2['Beth1']  # 如果字典中没有的键访问值,会输出以下错误
Traceback (most recent call last):
  File "<input>", line 1, in <module>
KeyError: 'Beth1'

3、修改字典

>>> dict1
{'a': 1, 'b': '3'}
>>> dict1['b'] = 666
>>> dict1
{'a': 1, 'b': 666}

4、删除字典元素

能删单一的元素也能清空字典,并且可以直接删除字典

>>> dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
>>> dict
{'Name': 'Zara', 'Age': 7, 'Class': 'First'}
>>> del(dict['Name'])  #删除键是'Name'的条目
>>> dict
{'Age': 7, 'Class': 'First'}
>>> dict.clear()  #清空词典所有条目
>>> dict
{}
>>> del(dict)  #删除词典

5、字典内置函数和方法

Python字典包含了以下内置函数:

cmp(dict1, dict2)  #比较两个字典元素。
len(dict)          #计算字典元素个数,即键的总数。
str(dict)          #输出字典可打印的字符串表示。
type(variable)     #返回输入的变量类型,如果变量是字典就返回字典类型。        

Python字典包含了以下内置方法:

dict.clear()                     #删除字典内所有元素
dict.copy()                   #返回一个字典的浅复制
radiansdict.fromkeys()            #创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
dict.get(key, default=None)        #返回指定键的值,如果值不在字典中返回default值
dict.has_key(key)                  #如果键在字典dict里返回true,否则返回false
dict.items()                  #以列表返回可遍历的(键, 值) 元组数组
dict.keys()                  #以列表返回一个字典所有的键
dict.setdefault(key, default=None)    #和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default
dict.update(dict2)                  #把字典dict2的键/值对更新到dict里
dict.values()                     #以列表返回字典中的所有值

四、集合

集合(set)是一个无序不重复元素的序列。

可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。

1、创建集合

#创建一个空集合
>>> set1 = set()
>>> set1
set()

#创建一个具有数据的集合
>>> set2 = {1, 'a', 'apple', 11.22}
>>> set2
{11.22, 1, 'apple', 'a'}

>>> set3 = set([1, 2, 3])
>>> set3
{1, 2, 3}

2、判断元素是否在集合内

>>> 'apple' in set2
True
>>> 'apple' not in set2
False

3、添加元素

#将值添加到集合中,如果值存在,则不作任何操作
>>> set2.add('car')
>>> set2
{1, 'apple', 'car', 11.22, 'a'}

#另外一种添加方式,参数可以是列表、元组、字典等
>>> set2.update({2,3})
>>> set2
{1, 'apple', 2, 3, 'car', 11.22, 'a'}

>>> set2.update([1,4],[5,6])
>>> set2
{1, 'apple', 2, 3, 4, 5, 6, 'car', 11.22, 'a'}

4、删除元素 

>>> set2.remove('car')
>>> set2
{1, 'apple', 2, 3, 4, 5, 6, 11.22, 'a'}

>>> set2.remove('hello') #如果元素不存在会发生错误
Traceback (most recent call last):
  File "<input>", line 1, in <module>
KeyError: 'hello'

#这种方式如果元素不存在不会发生错误
>>> set2.discard('hello')

5、计算集合元素个数

>>> len(set2)
9

6、清空集合

>>> set2.clear()
>>> set2
set()

猜你喜欢

转载自www.cnblogs.com/Jimc/p/9584606.html