Python——高级数据类型(七)
1. 列表数据类型的声明与访问
# coding=utf-8
#列表数据类型的声明与访问
my_list =[1,2,3,4,5] # 列表中的元素
print (my_list)
# 0 1 2 3 角标,索引 位置信息
my_list1 = ["a","b","c","d"]
print (my_list1)
print (my_list1[0])
print (my_list1[1])
my_list = [[1,2,3,4],["a","b","c","d"]]
print (my_list)
print (my_list[1])
print (my_list[1][0])
# 0 1 2 3 4 5 6 7 8
my_list = [1,2,3,4,5,"a","b","c","d"]
# -9 -8 -7 -6 -5 -4 -3 -2 -1
print (my_list)
print (my_list[:])
print (my_list[:2]) # 不包含右边
print (my_list[1:3]) # 包含左边的位置,不包含右边的位置
print (my_list [-1])
# 0 1 2 3 4 5 6 7 8
my_list = [1,2,3,4,5,"a","b","c","d"]
# -9 -8 -7 -6 -5 -4 -3 -2 -1
print (my_list [-2])
print (my_list [:-1])
print (my_list [1:-1])
print (my_list[6:-4])
print (my_list[5:-1])
print打印结果:[1, 2, 3, 4, 5]
['a', 'b', 'c', 'd']
a
b
[[1, 2, 3, 4], ['a', 'b', 'c', 'd']]
['a', 'b', 'c', 'd']
a
[1, 2, 3, 4, 5, 'a', 'b', 'c', 'd']
[1, 2, 3, 4, 5, 'a', 'b', 'c', 'd']
[1, 2]
[2, 3]
d
c
[1, 2, 3, 4, 5, 'a', 'b', 'c']
[2, 3, 4, 5, 'a', 'b', 'c']
[]
['a', 'b', 'c']
2. 列表数据类型元素的添加,更新和删除
# coding=utf-8
# 列表的元素的增加,删除和更新
my_list = [1,2,3,4,5,"a","b","c","d"]
# 列表元素的添加
my_list.append(10)
print (my_list)
# 列表元素的更新
my_list[1] = 'h'
print (my_list)
# 列表元素的删除
# 根据元素的值来删除
my_list.remove("c")
print (my_list)
# 根据索引值来删除
my_list.pop(1)
print (my_list)
print打印结果:
[1, 2, 3, 4, 5, 'a', 'b', 'c', 'd', 10]
[1, 'h', 3, 4, 5, 'a', 'b', 'c', 'd', 10]
[1, 'h', 3, 4, 5, 'a', 'b', 'd', 10]
[1, 3, 4, 5, 'a', 'b', 'd', 10]
3 元组数据类型
# coding=utf-8
# 元组数据类型
t = (1,2,3)
print (t[1])
# t .append(4)
# t[1] = 5
# t.remove(2)
# t.pop(1)
print (t)
"""
列表和元组的区别
列表允许增加,修改和删除操作
元组不允许增加,修改和删除操作
也就是说元组一旦声明了,就不允许更改了
"""
4 字典数据类型的声明与访问
# coding=utf-8
# 字典数据类型的声明与访问
# 下边这个样子的变量叫做字典
d ={
"a":"1", # 冒号前边的部分,我们叫做字典的key 键
"b":"2" # 冒号后边的部分,我们叫做字典的value 键
}
# 键值对儿
print (d)
print (type(d))
# 单独访问其所有的键
print (d.keys())
# 单独访问其所有的值
print (d.values())
# 我们可以根据字典的建议访问字典的值吗??
print (d['a'])
print打印结果:
{'a': '1', 'b': '2'}
<type 'dict'>
['a', 'b']
['1', '2']
1
5 字典数据类型增加、修改和删除操作
# coding=utf-8
# 字典数据类型增加、修改和删除操作
my_dict ={
1: "a",
2: "b",
3: "c"
}
dict1 = {
4: "d"
}
# 添加操作 update
my_dict.update(dict1)
print (my_dict)
# 更新值
my_dict[1] = "aaaaa"
print (my_dict)
# 字典的删除操作
my_dict.pop(2)
print (my_dict)
print打印结果:
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
{1: 'aaaaa', 2: 'b', 3: 'c', 4: 'd'}
{1: 'aaaaa', 3: 'c', 4: 'd'}
6 for循环
# coding=utf-8
# for 循环
# 01234
s = "abcde"
# 第一种
# print (s[0])
# 第二种
# for i in s:
# print (i)
l =["a","b","c","d"]
for i in s:
print (i)
t =("a","b","c","d")
for i in s:
print (i)
print打印结果:
a
b
c
d
e
a
b
c
d
e