Python数据结构(列表、字典、集合、元组)详细解析

Python数据结构(列表、字典、集合、元组)详细解析

列表

1.列表是Python中使用最频繁的数据类型
2.列表可以完成大多数集合类的数据结构实现。
3.列表中元素的类型可以不相同,它支持数字,字符串甚至可以包含列表(所谓嵌套)
4.和字符串一样,列表同样可以被索引和截取,列表被截取后返回一个包含所需元素的新列表
5.List内置了有很多方法,例如append()、pop()等等
6.List可以使用+操作符进行拼接
7.[注意]与Python字符串不一样的是,列表中的元素是可以改变的

基本操作函数

1.索引,切片,加,乘,检查成员
2.增加、删除、连接分割、排序倒序

list1=[1,2,3.0,4,5.0]
list2=['6','7','8','8','8']
list3=['One','Two','Three']
list4=[1,2,3]
print(len(list1))
print(list2.count('8'))
print(list1[0])
print(list1[-1])
print(list1[1:3])
print(list1[1:])
print(list1*2)
print(list1+list2)

if(1 in list1):
    print("1在列表list1中")

print('list1中最大元素对应下标为{0}'.format(list1.index(max(list1))))
print([list1,list2,list3])
##增加
list1.append(6)
list1.insert(2,2.5)
list1.extend([7,8])
print(list1)
##减小
del list1[2],list1[5]
list1.remove(7) #删除具体的值
pop_value=list1.pop(5)
print('pop_value={0}'.format(pop_value))
print(list1)
##连接与分割
join_list='--'.join(list2)  #join只能了解全是字符串的列表
print(join_list)
split_list=join_list.split('--',2)  #最后一个数字代表分割的次数,如果想全部分割则使用-1(默认)
print(split_list)

list1.reverse() #反向
print(list1)
list1.sort()    #排序
print(list1)

list_copy=list1.copy() 返回列表的浅复制,等于a[:]
5
3
1
5.0
[2, 3.0]
[2, 3.0, 4, 5.0]
[1, 2, 3.0, 4, 5.0, 1, 2, 3.0, 4, 5.0]
[1, 2, 3.0, 4, 5.0, '6', '7', '8', '8', '8']
1在列表list1中
list1中最大元素对应下标为4
[[1, 2, 3.0, 4, 5.0], ['6', '7', '8', '8', '8'], ['One', 'Two', 'Three']]
[1, 2, 2.5, 3.0, 4, 5.0, 6, 7, 8]
pop_value=8
[1, 2, 3.0, 4, 5.0]
6--7--8--8--8
['6', '7', '8--8--8']
[5.0, 4, 3.0, 2, 1]
[1, 2, 3.0, 4, 5.0]

迭代操作

1.zip两个列表操作
2.list映射解析
3.创建二维列表

for q,a in zip(list3,list4):
    print('{0}:{1}'.format(q,a))
    print('%s:%s'%(q,a))

print([elem*2 for elem in list1]) #list 的映射解析
print([[x, x**2] for x in list1])

def _add_str(str):
    return str+'_add'
print([_add_str(add_str) for add_str in list2])

list_filter=[elem for elem in list1 if elem !=2]
print(list_filter)

list5=['One','Two','Three']
list6=[1,2,3]
print(["{0}-{1}".format(x,y) for x in list5 for y in list6])

print(["{0}-{1}".format(list5[i],list6[i]) for i in range(len(list5))])

print([str(i) for i in range(1, 6)])

for i, v in enumerate(['tic', 'tac', 'toe']):
    print(i, v,end=";")
print('')
for i in reversed(range(1, 10, 2)):
    print(i,end=';')
print('')
for i in sorted(range(1, 10, 2)):
    print(i,end=';')
print('')   
print([i for i in range(4)])

a = (i for i in range(4))
print(next(a))
print(next(a))
One:1
One:1
Two:2
Two:2
Three:3
Three:3
[2, 4, 6.0, 8, 10.0]
[[1, 1], [2, 4], [3.0, 9.0], [4, 16], [5.0, 25.0]]
['6_add', '7_add', '8_add', '8_add', '8_add']
[1, 3.0, 4, 5.0]
['One-1', 'One-2', 'One-3', 'Two-1', 'Two-2', 'Two-3', 'Three-1', 'Three-2', 'Three-3']
['One-1', 'Two-2', 'Three-3']
['1', '2', '3', '4', '5']
0 tic;1 tac;2 toe;
9;7;5;3;1;
1;3;5;7;9;
[0, 1, 2, 3]
0
1

列表加深学习

列表推导式的执行顺序:各语句之间是嵌套关系,左边第二个语句是最外层,依次往右进一层,左边#第一条语句是最后一层
[x*y for x in range[1,5] if x > 2 for y in range[1,4] if x < 3]
他的执行顺序是
for x in range[1,5]
#if x > 2
#for y in range[1,4]
#if x < 3
#x*y

matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]
print(matrix)
print([[row[i] for row in matrix] for i in range(4)])
transposed = []
for i in range(4):
    transposed.append([row[i] for row in matrix])
print(transposed)

#创建二维列表格式:list_2d = [[0 for col in range(cols)] for row in range(rows)]
list_2d = [ [0 for i in range(5)] for i in range(5)]  #创建
print(list_2d)
list_2d[0].append(3)
list_2d[0].append(5)
print(list_2d)

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
[[0, 0, 0, 0, 0, 3, 5], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

字典和元组交互

##列表与字典
params_dict={'One':1,'Two':2,'Three':3}
list_parse_dict=['%s=%s'%(k,v) for k,v in params_dict.items()]
print(list_parse_dict)
##列表与元组
tuple = ( 'abcd', 786 , 2.23, 'runoob', 70.2 ) #元组
tuple_to_list=list(tuple)
print(tuple_to_list)
['One=1', 'Two=2', 'Three=3']
['abcd', 786, 2.23, 'runoob', 70.2]

元组

元组与列表的区别,元组它的关键是不可变性,元组提供了一种完整的约束。
1.[注意]元组(tuple)与列表类似,不同之处在于元组的元素不能修改
2.元组写在小括号(())里,元素之间用逗号隔开
3.元组中的元素值是不允许修改的,但我们可以对元组进行连接组合
4.函数的返回值一般为一个。而函数返回多个值的时候,是以元组的方式返回的

基本操作函数

tuple1 = ( '1', 'a' , 2.0, 'b', 3 )
#索引操作与列表一致
tuple0 = ()    # 空元组
tuple2 = (20,) # 一个元素,需要在元素后添加逗号
('abcd', 786, 2.23, 'runoob', 70.2)

集合

集合(set)是一个无序不重复元素的序列。基本功能是进行成员关系测试和删除重复元素
1.可以使用大括号{}或者set()函数创建集合,注意:创建一个空集合必须用 set() 而不是{},因为{}是用来创建一个空字典

基本操作函数

set1 = {'One', 'One', 'Two', 'Two', 'Three', 'Four','Five'}
print(set1) #输出集合,重复的元素被自动去掉
if('One' in set1) :
    print('One在集合set1中')
#集合运算
set2=set('abracadabra')
set3=set('alacazam')
print(set2)
print(set2 - set3) # a和b的差集
print(set2 | set3) # a和b的并集
print(set2 & set3) # a和b的交集
print(set2 ^ set3) # a和b中不同时存在的元素

{'Two', 'One', 'Four', 'Five', 'Three'}
One在集合set1中
{'c', 'd', 'r', 'a', 'b'}
{'b', 'd', 'r'}
{'c', 'd', 'l', 'r', 'm', 'z', 'a', 'b'}
{'c', 'a'}
{'d', 'b', 'm', 'l', 'z', 'r'}
{'c', 'd', 'r', 'a', 'b'}

字典

d = {key1 : value1, key2 : value2 }
1.字典是无序的对象集合,列表是有序的对象结合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
2.键(key)必须使用不可变类型。
3.管字典中有多少项,in操作符花费的时间都差不多
def example(d):
for c in d:
print(c)
其中:d 是一个字典对象

基本操作函数

dict = {}
dict['One'] = 1
dict[2] = 'Two'
dict['Three']=3
dict['Five']=5
dict2={'ONE':1, 'TWO':2, 'THREE': 3}

print(dict)
print(dict2)
del dict['Five']
print(dict)

print(dict['One'])
print(dict.keys())
print(dict.values())
for k,v in dict2.items():
    print(k,":",v)
dict.clear() #清空字典
del dict #删除字典
type(dict2)

dict_pop_key,dcit_pop_value=dict2.popitem()
print('pop-{0}:{1}'.format(dict_pop_key,dcit_pop_value))#随机返回并删除字典中的一对键和值(一般删除末尾对)
for k, v in dict2.items():
    print(k, v,end=";")


dict4={2:'Two',3:'Three',1:'One'}
sorted(dict4.keys())
{'One': 1, 2: 'Two', 'Three': 3, 'Five': 5}
{'ONE': 1, 'TWO': 2, 'THREE': 3}
{'One': 1, 2: 'Two', 'Three': 3}
1
dict_keys(['One', 2, 'Three'])
dict_values([1, 'Two', 3])
ONE : 1
TWO : 2
THREE : 3
pop-THREE:3
ONE 1;TWO 2;




[1, 2, 3]

字典加深学习

#字典是支持无限极嵌套的
citys={
    '北京':{
        '朝阳':['国贸','CBD','天阶','我爱我家','链接地产'],
        '海淀':['圆明园','苏州街','中关村','北京大学'],
        '昌平':['沙河','南口','小汤山',],
        '怀柔':['桃花','梅花','大山'],
        '密云':['密云A','密云B','密云C']
    },
    '河北':{
        '石家庄':['石家庄A','石家庄B','石家庄C','石家庄D','石家庄E'],
        '张家口':['张家口A','张家口B','张家口C'],
        '承德':['承德A','承德B','承德C','承德D']
    }
}
for i in citys['北京']:
    print(i)
print('-----------------------')
for i in citys['北京']['海淀']:
    print(i)
朝阳
海淀
昌平
怀柔
密云
-----------------------
圆明园
苏州街
中关村
北京大学

列表、元组、集合、字典相互转换

列表元组转其他

###列表转集合(去重)
list1 = [1,2,3,4]
print(set(list1))
#两个列表转字典
list1 = ['key1','key2','key3']
list2 = ['1','2','3']
print(dict(zip(list1,list2)))
#嵌套列表转字典
list3 = [['key1','value1'],['key2','value2'],['key3','value3']]
print(dict(list3))
# 列表、元组转字符串
list2 = ['a', 'a', 'b']
print(''.join(list2))
tup1 = ('a', 'a', 'b')
print(''.join(tup1))
{1, 2, 3, 4}
{'key1': '1', 'key2': '2', 'key3': '3'}
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
aab
aab

字典转其他

# 字典key和value互转
dic2 = {'a': 1, 'b': 2, 'c': 3}
print({value:key for key, value in dic2.items()})
{1: 'a', 2: 'b', 3: 'c'}

字符串转其他

# 字符串转列表
s = 'aabbcc'
print(list(s))
# 字符串转元组
print(tuple(s))
# 字符串转集合
print(set(s))
# 字符串转字典
dic = eval("{'name':'ljq', 'age':24}")
print(dic)
# 切分字符串
a = 'a b c'
a.split(' ')
['a', 'a', 'b', 'b', 'c', 'c']
('a', 'a', 'b', 'b', 'c', 'c')
{'b', 'a', 'c'}
{'name': 'ljq', 'age': 24}





['a', 'b', 'c']

辛苦总结:),第一次写博客。如果写的好,请支持我下面的资源

pycharm工程python调用OpenCV实现USB摄像头实时人脸检测
http://download.csdn.net/download/zou19900101/10208407
pycharm工程pyQt5使用matplotlib绘图源码
http://download.csdn.net/download/zou19900101/10207077
pyqt5快速入门教程
http://download.csdn.net/download/zou19900101/10197371
Qt编写高逼格弹幕
http://download.csdn.net/download/zou19900101/10145524
Qt高仿360界面设计
http://download.csdn.net/download/zou19900101/10145518
Qt编写跨平台串口通信(Window+Linux)
http://download.csdn.net/download/zou19900101/10145513
OpenCV两种方法显示中文
http://download.csdn.net/download/zou19900101/10010181
wrote by zoushaoyuan 2018-01-19

  • 5
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值