0
点赞
收藏
分享

微信扫一扫

3. python 列表、元组和字典


一、 序列简介

  • 序列是一种包含多项数据的数据结构
  • python常见序列类型包括字符串、元组、列表等
  • 其中字符串与元组是不可变的,而列表是可变的
  • 元组创建列表使用(),而列表使用[]

>>> my_tuple=('fff',20,'dddd')
>>> print(type(my_tuple))
<class 'tuple'>
>>> print(my_tuple)
('fff', 20, 'dddd')

>>> my_list=['fff',20,'dddd']
>>> print(type(my_list))
<class 'list'>
>>> print(my_list)
['fff', 20, 'dddd']

二、列表与元组通用用法

只要不涉及改变元素操作,列表与元组用法是相同的,下面以元组操作为例

1. 通过索引使用元素——同字符串

>>> my_tuple=('fff',20,'dddd')
>>> print(my_tuple[0])
fff
>>> print(my_tuple[-1])
dddd
>>> print(my_tuple[:2])
('fff', 20)
>>> print(my_tuple[1:])
(20, 'dddd')

#间隔为2
>>> print(my_tuple[0:3:2])
('fff', 'dddd')

2. 加法

  • 元组(列表)的加法是将多个元组(列表)的值合并在一起
  • 元组不能与列表直接相加

>>> tuple1=(555,'dads',344,'aaa')
>>> tuple2=(666,'dads',888,'dddaa')
>>> print(tuple1+tuple2)
(555, 'dads', 344, 'aaa', 666, 'dads', 888, 'dddaa')
>>> print(tuple1)
(555, 'dads', 344, 'aaa')
>>> print(tuple2)
(666, 'dads', 888, 'dddaa')

3. 乘法

元组(列表)的乘法是将其中元素的值重复n次

>>> print(tuple1*3)
(555, 'dads', 344, 'aaa', 555, 'dads', 344, 'aaa', 555, 'dads', 344, 'aaa')

4. in,len(),min(),max()用法与字符串相同

5. 序列封包与序列解包

  • 序列封包:将多个值赋给一个变量时,python会自动将多个值封装为元组
  • 序列解包:允许将元组或列表之间赋给多个变量,此时其中元素会依次赋值给各个变量(数量需相同)

>>> a=12,'dsada',15
>>> print(a)
(12, 'dsada', 15)

>>> x,y,z=a
>>> print(x)
12
>>> print(y)
dsada
>>> print(z)
15

序列解包也允许只解出部分变量,其余变量使用列表保存。在变量前添加*则该变量代表一个列表

>>> mylist=[1,2,3,4,5,6]
>>> x,*y,z=mylist
>>> print(x)
1
>>> print(y)
[2, 3, 4, 5]
>>> print(z)
6

6. 序列转换

将对象转换为列表 list()

>>> tuple=(1,2,3,4)
>>> list=list(tuple)
>>> print(list)
[1, 2, 3, 4]

将对象转换为元组 tuple()

a_list=[1,2,3,4,5]
tuple2=tuple(a_list)
print(tuple2)   #(1, 2, 3, 4, 5)

三、 列表专用用法

1. 增加元素

append——追加至列表最后面,会将追加元素当作一个整体

>>> mylist=[323,'dasda',444]
>>> mylist.append('rrr')
>>> print(mylist)
[323, 'dasda', 444, 'rrr']
>>> mylist.append((1,5,8))
>>> print(mylist)
[323, 'dasda', 444, 'rrr', (1, 5, 8)]
>>> mylist.append([66,'fdfs'])
>>> print(mylist)
[323, 'dasda', 444, 'rrr', (1, 5, 8), [66, 'fdfs']]

extend——追加至列表最后面,会分别追加其中每个元素

>>> mylist=[323,'dasda',444]
>>> mylist.extend('rrr')
>>> print(mylist)
[323, 'dasda', 444, 'r', 'r', 'r']
>>> mylist.extend((1,5,8))
>>> print(mylist)
[323, 'dasda', 444, 'r', 'r', 'r', 1, 5, 8]
>>> mylist.extend([66,'fdfs'])
>>> print(mylist)
[323, 'dasda', 444, 'r', 'r', 'r', 1, 5, 8, 66, 'fdfs']

insert——在指定位置增加元素

>>> mylist=[1,2,3,4,5]
>>> mylist.insert(3,'yyy')
>>> print(mylist)
[1, 2, 3, 'yyy', 4, 5]
>>> mylist.insert(3,(444,666))
>>> print(mylist)
[1, 2, 3, (444, 666), 'yyy', 4, 5]

2. 删除元素

del语句——可删除一个元素,也可删除列表中的一段

>>> print(mylist)
[1, 2, 3, (444, 666), 'yyy', 4, 5]

>>> del mylist[2]
>>> print(mylist)
[1, 2, (444, 666), 'yyy', 4, 5]

#删除索引为3-5的元素(不含5)
>>> del mylist[3:5]
>>> print(mylist)
[1, 2, (444, 666), 5]

#删除索引为0-5的元素,间隔为2(不含5)
>>> del mylist[0:5:2]
>>> print(mylist)
[2, 5]

remove()方法——根据给定值在列表中查找并删除第一次找到的值,若找不到对应值会报错

>>> mylist=[1,2,3,3,3,4,5]
>>> mylist.remove(3)
>>> print(mylist)
[1, 2, 3, 3, 4, 5]
>>> mylist.remove('ff')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list

clear()方法——清空列表

>>> print(mylist)
[1, 2, 3, 3, 4, 5]
>>> mylist.clear()
>>> print(mylist)
[]

3. 修改元素

非常简单,直接赋值

>>> mylist=[1,2,3,3,3,4,5]
>>> mylist[3]=666
>>> print(mylist)
[1, 2, 3, 666, 3, 4, 5]

#将索引为1,2对应元素换为x,y
>>> mylist[1:3]='xy'
>>> print(mylist)
[1, 'x', 'y', 666, 3, 4, 5]

#将索引为1对应元素换为a,b,c,d,e
>>> mylist[1:2]='abcde'
>>> print(mylist)
[1, 'a', 'b', 'c', 'd', 'e', 'y', 666, 3, 4, 5]

4. 其他常用方法

>>> print(mylist)
[1, 'a', 'b', 'c', 'd', 'e', 'y', 666, 3, 4, 5]

#统计元素个数
>>> print(mylist.count('d'))
1

#查找元素位置
>>> print(mylist.index('d'))
4

#指定查找范围,若找不到会报错
>>> print(mylist.index('d',5,7))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'd' is not in list
>>>

#按后进先出删除元素
>>> print(mylist.pop())
5
>>> print(mylist.pop())
4
>>> print(mylist)
[1, 'a', 'b', 'c', 'd', 'e', 'y', 666, 3]

#翻转元素
>>> print(mylist.reverse())
None
>>> print(mylist)
[3, 666, 'y', 'e', 'd', 'c', 'b', 'a', 1]
>> mylist.reverse()
>>> print(mylist)
[1, 'a', 'b', 'c', 'd', 'e', 'y', 666, 3]

#将元素排序,字符串与数值一起排会报错
>>> mylist.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'int'

>>> a_list=[2,4,6,8,3,4,1]
>>> a_list.sort()
>>> print(a_list)
[1, 2, 3, 4, 4, 6, 8]
#逆序排序
>>> a_list.sort(reverse=True)
>>> print(a_list)
[8, 6, 4, 4, 3, 2, 1]

#字符串默认按ASCII码排序
>>> b_list=['a','rrr','aaa','bb']
>>> b_list.sort()
>>> print(b_list)
['a', 'aaa', 'bb', 'rrr']

#按字符串长度排序(逆序)
>>> b_list.sort(key=len,reverse=True)
>>> print(b_list)
['aaa', 'rrr', 'bb', 'a']

四、字典用法

存放具有映射关系的数据,是一些键值对。

1. 创建字典

使用{}创建

>>> score={'math':89,'english':95}
>>> print(score)
{'math': 89, 'english': 95}
>>> print(type(score))
<class 'dict'>

#key值可为元组
>>> dict={(20,30):'fff',30:'good'}
>>> print(dict)
{(20, 30): 'fff', 30: 'good'}

#key值不能为列表(因为列表值可变)
>>> dict={[20,30]:'fff',30:'good'}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

使用dict()函数创建

price=[('book',20),('pen',5)]
dict1=dict(price)
print(dict1)      #{'book': 20, 'pen': 5} 

cars=[['BMW',100],['BENZ',900],['AUDI',50]]
dict2=dict(cars)
print(dict2)      #{'BMW': 100, 'BENZ': 900, 'AUDI': 50}

dict3=dict(BMW=100,BENZ=900)
print(dict3)      #{'BMW': 100, 'BENZ': 900}

2. 字典的基本用法

程序对字典的操作都是基于key的

#添加k-v对,只需为不存在的key赋值;对已存在key赋值则为替换
dict1={'book':20,'pen':5}
dict1['new']=100
print(dict1)             #{'book': 20, 'pen': 5, 'new': 100}
dict1['new']=300
print(dict1)             #{'book': 20, 'pen': 5, 'new': 300}

#删除k-v对,使用del语句
del dict1['book']
print(dict1)             #{'pen': 5, 'new': 300}

#判断字典是否包含指定key
print('book' in dict1)   #False
print('pen' in dict1)    #True

3. 字典常用方法

>>> dir(dict)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

#fromkeys(),使用给定的多个key创建字典(默认value为None,也可额外指定)
dict1=dict.fromkeys(['a','b','c'])
print(dict1)                              #{'a': None, 'b': None, 'c': None}
dict2=dict.fromkeys(['a','b','c'],111)
print(dict2)                              #{'a': 111, 'b': 111, 'c': 111}

#get(),通过key获取value值
dict1={'book':20,'pen':5}
print(dict1.get('book'))  #20
print(dict1.get('new'))   #None

#setdefault(),用于为不存在的key设置默认值,同时将k-v对插入字典
print(dict1)                              #{'book': 20, 'pen': 5}
print(dict1.setdefault('new',222))        #222
print(dict1)                              #{'book': 20, 'pen': 5, 'new': 222}

#update(),使用另一个字典更新现有字典。
dict1.update({'book':100,'new':111}) 
#若key值在原字典中存在,则只更新value;若key值在原字典中不存在,新插入一个k-v对
print(dict1) #{'book': 100, 'pen': 5, 'new': 111}

#items(),获取字典中所有k-v对
print(dict1.items())          #dict_items([('book', 100), ('pen', 5), ('new', 111)])
print(type(dict1.items()))    #<class 'dict_items'>

#keys(),获取字典中所有key值
print(dict1.keys())           #dict_keys(['book', 'pen', 'new'])
print(type(dict1.keys()))     #<class 'dict_keys'>

#values(),获取字典中所有value值
print(dict1.values())         #dict_values([100, 5, 111])
print(type(dict1.values()))   #<class 'dict_values'>

 

举报

相关推荐

0 条评论