jupyther_python基础系列04 第四章 组合数据类型

第一部分列表

列表

列表的表达

  • 序列类型: 内部元素有位置关系, 能通过位置序号访问其中元素
  • 列表是一个可以使用多种类型元素, 支持元素的增, 删, 查, 改的序列
ls = ["Python", 1989, True, {"vewsion": 3.73,"date": 2020}]
for i in ls:
    print(i)
Python
1989
True
{'vewsion': 3.73, 'date': 2020}
  • 另一种产生方式: list(可迭代对象) (字符串, 元组, 集合, range())
# 字符串转列表
list("人工智能你好")
['vewsion', 'date']
# 元组转列表
list((10, 20, 30, 40))
[10, 20, 30, 40]
# 集合转列表
list({10, 10, 2, 0, 30, 1, 22})
[0, 1, 2, 10, 22, 30]
# range()转列表
list(range(1, 10, 2))
[1, 3, 5, 7, 9]
  • range(起始数字,终止数字,数字间隔)
for i in range(1, 10, 2):
    print(i)
1
3
5
7
9

列表的性质

  • 列表的长度
len([1, 2, 3, 4, 5])
5
  • 列表的索引----与字符串相同

变量名[位置编号]

cars = ["BYD", "BMW", "AUDI", "TOYOTA"]
print(cars[0])
print(cars[-1])
BYD
TOYOTA
  • 列表的切片

变量名[开始位置: 结束位置: 切片间隔]

 cars = ["BYD", "BMW", "AUDI", "TOYOTA"]
cars[0:4:2]
['BYD', 'AUDI']
print(cars[:3])
print(cars[1:4:2])
print(cars[:])
print(cars[-4:-2])


print(cars[:-4:-1])
print(cars[::-1])
['BYD', 'BMW', 'AUDI']
['BMW', 'TOYOTA']
['BYD', 'BMW', 'AUDI', 'TOYOTA']
['BYD', 'BMW']
['TOYOTA', 'AUDI', 'BMW']
['TOYOTA', 'AUDI', 'BMW', 'BYD']

列表的操作符

  • 用 list1 + list2 实现拼接
list1 = [1, 2, 3, 4]
list2 = ["a", "b", "c", "d"]
list1 + list2
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-5-9d4f2030fea9> in <module>
      2 list2 = ["a", "b", "c", "d"]
      3 list1 + list2
----> 4 "123".join(lis1)


NameError: name 'lis1' is not defined
  • 用 n*list 实现复制
list1 * 3
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
  • 初始化列表的一种方式
[0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

列表的操作方法

1 增加元素

  • 在末尾增加元素-----列表.append(新增元素)
languages = ["Python", "C++", "Java"]
languages.append("R")
print(languages)
['Python', 'C++', 'Java', 'R']

append将列表2作为一个元素添加到列表1中

languages.append(["PHP","Basic"])
languages
['Python', 'C', 'C++', 'Java', 'R', ['PHP', 'Basic']]
  • 在任意位置插入元素 —列表.insert(位置, 元素)
    在位置钱插入元素
languages.insert(1,"C")
languages
['Python', 'C', 'C++', 'Java', 'R']
  • 在末尾整体并入另一个列表----列表1.extend(列表2)
l1 = ['Python', 'C', 'C++']
l1.extend(["Java","R"])
l1
['Python', 'C', 'C++', 'Java', 'RecursionError']

2. 删除元素

  • 删除列表i位置的元素 列表.pop(位置)
languages = ['Python', 'C', 'C++', 'Java', 'R']
languages.pop(1)
print(languages)
['Python', 'C++', 'Java', 'R']
  • 不写位置,默认最后一个元素
languages.pop()
languages
['Python', 'C++', 'Java']
  • 删除列表中的第一次出现的某元素 列表.remove(待删除)
languages = ['Python', 'C', 'C++', 'C', 'R','C']
languages.remove('C')
languages
['Python', 'C++', 'C', 'R', 'C']
languages = ['Python', 'C', 'C++', 'C', 'R','C']
while "C" in languages:
    languages.remove('C')
languages
['Python', 'C++', 'R']

3.查找元素

  • 列表中的第一次出现的某元素位置 列表.index(待查元素)
languages = ['Python', 'C', 'C++', 'Java', 'R']
index = languages.index("R")
index
4

4.修改元素

  • 通过先索引后赋值的方式,对元素进行修改 列表名[位置]=新值
languages = ['Python', 'C', 'C++', 'R']
languages[1] = "C#"
languages
['Python', 'C#', 'C++', 'R']

5.列表的赋值

  • 错误的方式
languages = ['Python', 'C', 'C++', 'R']
languages2 = languages
languages2
['Python', 'C', 'C++', 'R']
languages.pop()
print(languages)
print(languages2)
# 
['Python', 'C']
['Python', 'C']
- 正确的方法 
1. 列表.copy()
languages = ['Python', 'C', 'C++', 'R']
languages2 = languages.copy()
languages.pop()
print(languages)
print(languages2)
['Python', 'C', 'C++']
['Python', 'C', 'C++', 'R']
  1. 列表[:]
languages = ['Python', 'C', 'C++', 'R']
languages2 = languages[:]
languages.pop()
print(languages)
print(languages2)
['Python', 'C', 'C++']
['Python', 'C', 'C++', 'R']

6.列表的排序

  • 直接使用.sort()对列表进行永久排序
  • 直接在列表上操作,无返回值
ls = [2, 1, 4, 5, 6, 3, 8, 7, 9, 0]
ls.sort()
ls
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  • 递减排序
ls.sort(reverse=True)
ls
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
  • 使用sorted(列表)对列表进行临时排序
  • 原列表不变,返回排序后的列表
ls = [2, 1, 4, 5, 6, 3, 8, 7, 9, 0]
ls_2 = sorted(ls)
print(ls)
print(ls_2)
[2, 1, 4, 5, 6, 3, 8, 7, 9, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

7.列表的反转

lr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(lr[::-1])
lr
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]





[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
lr.reverse()
lr
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

8.for循环进行遍历

for i in lr:
    print(i)
9
8
7
6
5
4
3
2
1
0

元组

元组的表达

  • 元组是一个可以使用多种类型元素, 一旦定义, 内部元素不支持增删查改的序列类型(不可变的列表)
names = ("zhang", "Peter", "Pual")
names
('zhang', 'Peter', 'Pual')

元组的操作

  • 不支持元素增加,删除,修改
  • 其他操作与列表一致
age = (10,2,5,12,13,7)

---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-25-53249160d83e> in <module>
      1 age = (10,2,5,12,13,7)
----> 2 age.sort()
      3 age


AttributeError: 'tuple' object has no attribute 'sort'

元组的场景用处

打包 解包

def f1(x):  #返回x的平方和立方
    return x**2, x**3  #实现打包返回


print(f1(3))
print(type(f1(3)))  #元组类型
(27, 27)
<class 'tuple'>
a, b = f1(3) # 解包赋值
print(a)
print(b)
27
27

例子

numbers = [2001, 2002, 2003]
names = ["小明", "小红", "小强"]
list(zip(names, numbers))
[('小明', 2001), ('小红', 2002), ('小强', 2003)]
for number, name in zip(names, numbers):
    print(name, number)
2001 小明
2002 小红
2003 小强

字典

字典的表达

  • 映射类型: 通过"键"-"值"的映射实现数据存储和查找
  • 常规字典是无序的
students = {1001: "小明", 1002: "小红", 1003: "小强"}
students
{1001: '小明', 1002: '小红', 1003: '小强'}

字典键的要求

    1. 字典的键不能重复
students = {1001: "小明", 1001: "小红", 1003: "小强"}
students
'小红'
    1. 字典的键必须是不可变类型
  • 不可变类型: 数字, 字符串, 元组

  • 可变类型: 列表, 字典, 集合

# d = [[1, 2]: 3]
  File "<ipython-input-34-d6df521dc613>", line 1
    d = [[1, 2]: 3]
               ^
SyntaxError: invalid syntax

字典的性质

  • 字典的长度—键值对的个数
students = {1001: "小明", 1002: "小红", 1003: "小强"}
len(students)
3
  • 字典的索引

通过字典[键]的形式

students = {1001: "小明", 1002: "小红", 1003: "小强"}
students[1001]
'小明'

字典的操作方法

  1. 增加键值对
  • 变量名[新键]=新值
students = {1001: "小明", 1002: "小红", 1003: "小强"}
students[1004]="小飞"
students
{1001: '小明', 1002: '小红', 1003: '小强', 1004: '小飞'}
  1. 删除键值对
  • 通过del 变量名[删除键]
students = {1001: "小明", 1002: "小红", 1003: "小强"}
del students[1002]
students
{1001: '小明', 1003: '小强'}
  • 通过变量名.pop(删除键)
students = {1001: "小明", 1002: "小红", 1003: "小强"}
value = students.pop(1001)
print(value)
print(students)
小明
{1002: '小红', 1003: '小强'}
  • 变量名.popitem() 随机删除一个键值对,并以元组返回删除键值对
students = {1001: "小明", 1002: "小红", 1003: "小强"}
key, value = students.popitem()
print(key, value)
print(students)
1003 小强
{1001: '小明', 1002: '小红'}
  1. 修改值
  • 通过先索引后赋值
students = {1001: "小明", 1002: "小红", 1003: "小强"}
students[1002] = "小雪"
students
{1001: '小明', 1002: '小雪', 1003: '小强'}
  1. d.get(key, default)方法 从字典d中获取键key对应的值,如果没有值,返回default
s = "牛奶奶找刘奶奶买牛奶"
d = {}
for i in s:
    d[i] = d.get(i, 0) + 1
print(d)
{'牛': 2, '奶': 5, '找': 1, '刘': 1, '买': 1}
  1. d.keys() d.values()
students = {1001: "小明", 1002: "小红", 1003: "小强"}
print(list(students.keys()))
print(list(students.values()))
[1001, 1002, 1003]
['小明', '小红', '小强']
小明
小红
小强
  1. d.items()方法及字典的遍历
students = {1001: "小明", 1002: "小红", 1003: "小强"}
print(list(students.items()))
for k, v in students.items():
    print(k, v)
[(1001, '小明'), (1002, '小红'), (1003, '小强')]
1001 小明
1002 小红
1003 小强

集合

集合的表达

  • 一系列互不相等元素的无序集合
  • 元素必须是不可变类型: 数字, 字符串, 元组, 可视作字典的键
  • 可以看作没有值, 或者值为None的字典
students = {"小明", "小红", "小强", "小明"}
students
{'小强', '小明', '小红'}

集合的运算

  • 通过集合进行交集并集的运算
ChineseA = {"刘德华", "张学友", "张曼玉", "古天乐", "林青霞"}
ChineseA
{'刘德华', '古天乐', '张学友', '张曼玉', '林青霞'}
Math_A = {"刘德华", "郭富城", "王祖贤", "古天乐", "林青霞", "黎明"}
Math_A
{'刘德华', '古天乐', '林青霞', '王祖贤', '郭富城', '黎明'}
ChineseA & Math_A   #  $  交集
{'刘德华', '古天乐', '林青霞'}
ChineseA | Math_A   #  | 并集
{'刘德华', '古天乐', '张学友', '张曼玉', '林青霞', '王祖贤', '郭富城', '黎明'}
ChineseA ^ Math_A   #  S ^ T 返回S和T中的非共同元素 
{'张学友', '张曼玉', '王祖贤', '郭富城', '黎明'}
ChineseA - Math_A   #  S - T 返回S中且不再T中的元素 
{'张学友', '张曼玉'}
  • 集合的遍历
for s in ChineseA | Math_A:
    print(s)
张曼玉
林青霞
郭富城
张学友
古天乐
黎明
刘德华
王祖贤

习题

list = []
for i in range(101):
    if (i % 2 == 0):
        list.append(i)
print(list)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]
ls = ["a","b","c","d","e"]
print(ls[2])
print(ls[-3])
c
c
print(ls[1:4:2])
['b', 'd']
print(ls[::-1])
['e', 'd', 'c', 'b', 'a']
cars = ["BYD", "GEELY"]
cars.append("TOYOTA")
print(cars)
['BYD', 'GEELY', 'TOYOTA']
cars.insert(1, "CHERY")
print(cars)
['BYD', 'CHERY', 'GEELY', 'TOYOTA']
cars.extend(["BMW", "BENZ"])
print(cars)
['BYD', 'CHERY', 'GEELY', 'TOYOTA', 'BMW', 'BENZ']
cars.remove(cars[0])
cars.remove(cars[5])
print(cars)
---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

<ipython-input-50-0c5393be45c9> in <module>
      1 cars.remove(cars[0])
----> 2 cars.remove(cars[5])
      3 print(cars)


IndexError: list index out of range
cars.remove("GEELY")
print(cars)
['CHERY', 'TOYOTA', 'BMW', 'BENZ']
print(cars.index("BMW"))
2
cars[cars.index("CHERY")] = "QQ"
print(cars)
['QQ', 'TOYOTA', 'BMW', 'BENZ']
cars2 = cars.copy()
print(cars2)
['QQ', 'TOYOTA', 'BMW', 'BENZ']
print(sorted(cars))
print(cars)
print(cars2.sort())
print(cars2)
['BENZ', 'BMW', 'QQ', 'TOYOTA']
['QQ', 'TOYOTA', 'BMW', 'BENZ']
None
['BENZ', 'BMW', 'QQ', 'TOYOTA']
for car in cars:
    print("My first car is {}".format(car))
My first car is QQ
My first car is TOYOTA
My first car is BMW
My first car is BENZ
foods = ["bread", "fish", "potato"]
prices = [2.4, 9.8, 0.9]

for food, price in zip(foods, prices):
    print("The price of {} is {}".format(food, price))
The price of bread is 2.4
The price of fish is 9.8
The price of potato is 0.9
str = "八百标兵奔北坡,炮兵并排北边跑。炮兵怕把标兵碰,\
        标兵怕碰炮兵炮。八了百了标了兵了奔了北了坡,\
        炮了兵了并了排了北了边了跑。炮了兵了怕了把了标了兵了碰,\
        标了兵了怕了碰了炮了兵了炮"
dic = {}
for s in str:
    dic[s] = dic.get(s,0)+1
print(dic)
{'八': 2, '百': 2, '标': 6, '兵': 12, '奔': 2, '北': 4, '坡': 2, ',': 4, '炮': 8, '并': 2, '排': 2, '边': 2, '跑': 2, '。': 3, '怕': 4, '把': 2, '碰': 4, ' ': 24, '了': 24}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值