元组、列表、字典

元组和列表中的数据是通过偏移量提取,字典中的数据是用字典的键提取的。

元组:只支持查询元素,不支持增加、修改和删除元素。

tuple1 = ('A','B')
#从元组中提取元素
print(tuple1[0])
print(tuple1[:])

#输出:
A
('A', 'B')
 1 tup1 = (12, 34.56)
 2 tup2 = ('abc', 'xyz')
 3 
 4 # 创建一个新的元组
 5 tup3 = tup1 + tup2
 6 print (tup3)
 7 #输出:(12, 34.56, 'abc', 'xyz')
 8 
 9 #删除元组
10 tup = ('physics', 'chemistry', 1997, 2000)
11 print (tup)
12 #输出:('physics', 'chemistry', 1997, 2000)
13 
14 del tup
15 print (tup)
16 #输出:
17 Traceback (most recent call last):
18   File "d:/py case/1.py", line 14, in <module>
19     print (tup)
20 NameError: name 'tup' is not defined

tuple()方法

语法:tuple( seq ),参数:seq -- 要转换为元组的序列,返回值:元组。
 1 #tuple()方法:将序列转换为元组,tuple() 函数不是改变值的类型,而是返回改变类型后的值,原值不会被改变
 2 #将列表转换为元组
 3 a=[1,2,3,4]
 4 a1=tuple(a)
 5 print(a)
 6 print(a1)
 7 
 8 #针对字典 会返回字典的key组成的tuple
 9 b={1:2,3:4}
10 b1=tuple(b)   
11 print(b)
12 print(b1) 
13 
14 #元组会返回元组自身
15 c=(1,2,3,4)
16 c1=tuple(c) 
17 print(c)
18 print(c1)  
19 
20 输出:
21 [1, 2, 3, 4]
22 (1, 2, 3, 4)
23 {1: 2, 3: 4}
24 (1, 3)
25 (1, 2, 3, 4)
26 (1, 2, 3, 4)

列表:用偏移量定位元素,偏移量从0开始,列表切片规则:左取右不取

append每次只能追加一个元素。del语句非常方便,既能删除一个元素,也能一次删除多个元素(原理和切片类似,左取右不取)

 1 a=[1,2,4,5,7,'abc']
 2 
 3 #从列表提取单个元素
 4 print(a[0])
 5 输出:1
 6 
 7 #从列表提取多个元素
 8 print(a[:2])
 9 输出:[1, 2]
10 
11 print(a[1:4])
12 输出:[2, 4, 5]
13 
14 #给列表增加元素
15 a.append(8)
16 print(a)
17 输出:[1, 2, 4, 5, 7, 'abc', 8]
18 
19 #给列表删除元素
20 del a[:]
21 print(a)
22 输出:[]

 具体用法查看链接:https://www.runoob.com/python/python-lists.html

len()函数:得出一个元组、列表或者字典的长度(元素个数),括号里放元组、列表或字典名称

1 students = ['小明','小红','小刚']
2 scores = {'小明':95,'小红':90,'小刚':90}
3 print(len(students))
4 #输出:3
5 print(len(scores))
6 #输出:3

字典:由键值对组成,字典中的键具备唯一性,而值可重复。

scores = {'小明':95,'小红':90,'小刚':90}
#从字典中提取元素
print(scores['小明'])
#输出:95

#给字典增加/删除元素
scores['小青']=95
print(scores)
#输出:{'小明': 95, '小红': 90, '小刚': 90, '小青': 95}

del scores['小明']
print(scores)
#输出:{'小红': 90, '小刚': 90, '小青': 95}

 字典内置函数&方法查看:https://www.runoob.com/python/python-dictionary.html

猜你喜欢

转载自www.cnblogs.com/String-song/p/11928081.html