3.1数据结构—元组和列表

#3.1数据结构和序列
#3.1.1元组:固定长度,不可改变
#创建元组tuple
tup1 = (1,2,3)
tup2 = ((1,2),3,4)
tup1
tup2
((1, 2), 3, 4)
#序列或迭代器转换为元组
tup3 = tuple([1,2,3])
tup4 = tuple("string")
tup3
tup4
('s', 't', 'r', 'i', 'n', 'g')
#访问元素
tup4[0]
's'
#加号串联元组
tup5 = tup1 + tup2
tup5
(1, 2, 3, (1, 2), 3, 4)
#乘号复制元组
tup6 = tup1 * 4
tup6
(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)
#元组元素赋给类似元组的变量
a,b,c = tup1
((a,b),c,d) = tup2
d
4
#元组拆分
values = (1,2,3,4,5)
a,b,*rest = values
rest
[3, 4, 5]
#tuple方法
a = (1,2,3,3,4,4,4,5)
a.count(4)  #计算频率
3
#3.1.2 列表 长度可变,内容可修改
#创建列表list
a_list = [2,3,7,None]
tup = ("foo","bar","baz")
b_list = list(tup)
b_list
['foo', 'bar', 'baz']
#修改列表
b_list[1] = "peekkaboo"
b_list
['foo', 'peekkaboo', 'baz']
#利用列表实体化迭代器
gen = range(10)
gen
range(0, 10)
list(gen)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#添加删除元素
b_list.append("dwarf")
b_list
['foo', 'peekkaboo', 'baz', 'dwarf']
b_list.insert(1,"red")
b_list
['foo', 'red', 'peekkaboo', 'baz', 'dwarf']
b_list.pop(2)
b_list
['foo', 'red', 'baz', 'dwarf']
b_list.append("fool")
b_list.remove("fool")
b_list
['foo', 'red', 'baz', 'dwarf']
#检查列表值
"dwarf" in b_list
True
#串联和组合列表
[1,None,'fool'] + [2,(2,3),5]
[1, None, 'fool', 2, (2, 3), 5]
x = [4,None,'fool']
x.extend([2,(2,3),5])
x
[4, None, 'fool', 2, (2, 3), 5]
#排序
a = [2,5,1,6,4,8,9,3,1]
a.sort()
a
[1, 1, 2, 3, 4, 5, 6, 8, 9]
b = ['saw','small','He','foxe','foxes']
b.sort(key = len)
b
['He', 'saw', 'foxe', 'small', 'foxes']
#切片
seq = [7,2,3,7,5,6,0,1]
seq[1:5]
[2, 3, 7, 5]
seq[:5]
[7, 2, 3, 7, 5]
seq[3:]
[7, 5, 6, 0, 1]
seq[-4:]
[5, 6, 0, 1]
seq[-6:-2]
[3, 7, 5, 6]
seq[::2]
[7, 3, 5, 0]
seq[0:4:2]
[7, 3]
seq[::-1]
[1, 0, 6, 5, 7, 3, 2, 7]
#序列函数
#enumerate函数返回(i,value)元组序列
some_list = ['foo','bar','baz']
mapping = {}
for i,v in enumerate(some_list):
    mapping[v] = i
mapping
{'foo': 0, 'bar': 1, 'baz': 2}
#sorted函数返回新的排好序的列表
sorted([7,4,5,3,5,1,8,6,3])

[1, 3, 3, 4, 5, 5, 6, 7, 8]
#zip函数将多个列表元组或其他序列组合成元组列表
seq1 = ['foo','bar','baz']
seq2 = ['one','two','three']
zipped = zip(seq1,seq2)
list(zipped)
[('foo', 'one'), ('bar', 'two'), ('baz', 'three')]
seq3 = [False,True]
list(zip(seq1,seq2,seq3))
[('foo', 'one', False), ('bar', 'two', True)]
for i,(a,b) in enumerate(zip(seq1,seq2)):
    print("{0}:,{1}:,{2}".format(i,a,b))
0:,foo:,one
1:,bar:,two
2:,baz:,three
pitchers = [('Nolan','Ryan'),('Roger','Clemens'),('Schilling','Curt')]
first_names,last_names = zip(*pitchers)
first_names
('Nolan', 'Roger', 'Schilling')
#reversed函数
list(reversed(range(10)))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

猜你喜欢

转载自blog.csdn.net/DMU_lzq1996/article/details/83279070
今日推荐