视频:

上午:https://ke.qq.com/webcourse/index.html#cid=2744006&term_id=102851992&lite=1&from=800021724&taid=34409921&vid=5285890806630147557
下午:https://ke.qq.com/webcourse/index.html#cid=2744006&term_id=102851992&lite=1&from=800021724&taid=34412885&vid=5285890806628922388

上一天内容复习

  • 格式化字符串的操作 ```python height = 100 width = 38

    计算四边形的周长

    print((height+width)*2)

print(‘四边形的周长为: {}’.format((width+height)*2))

print(f’四边形的周长为: {(width+height)*2}’)

  1. - 索引,切片,步长
  2. 从左往右来看,和从右向左来看,值一样。那么这个数我们称为回文数。
  3. ```python
  4. num = 1789781
  5. # 如何判断num是否为回文数
  6. # 将数字转换为字符串
  7. str_num = str(num)
  8. print(type(str_num))
  9. # 字符串使用步长操作倒序
  10. print(str_num[::-1])
  11. # 如果两个字符串的值相等
  12. if str_num == str_num[::-1]:
  13. print(f'{num} 为回文数')
  14. else:
  15. print(f'{num} 不是回文数')

创建Pycharm 项目

image.png

str 字符串的常用方法

  • count 方法, 统计字符在字符串中出现的次数; ```python words = “”” There are so many programming languages, and every language has its own features. But all of them have one thing in common: they process data. From a simple calculator to supercomputers, they all work on data.

It’s the same with humans: there are so many countries, so many cultures, and so much knowledge within each community.

But to communicate with other communities, people need a common medium. Language is to humans what JSON is to programming, a common medium of data transmission.

What is JSON? JSON stands for JavaScript Object Notation. So before understanding JSON let’s understand objects in JavaScript.

Every programming language has some method of storing similar data together. In C, for example, they are called structures.

In JavaScript, objects are a collection of key-value pairs, where values can be any variable (number, string, boolean), another object, or even a function. Objects are very useful in object-oriented programming.

Object-oriented programming is a programming paradigm based on the concept of “objects”, which can contain data, in the form of fields, and code, in the form of procedures. Let’s look at an example.

In JavaScript, objects are defined using curly braces, for example: “”” count1 = words.count(‘to’) print(count1)

指定搜索位置 1-100, 跟切片原理一样

count2= words.count(‘to’,1,100) print(count2)

  1. - center 指定字符填充中间位置
  2. ```python
  3. s = "购物小票"
  4. s1 = s.center(50,'-')
  5. print(s1)
  6. -----------------------购物小票-----------------------
  • upper 转换为大写
  • lower 转换为小写

    1. s = 'Get'
    2. # 转换为大写
    3. s1 = s.upper()
    4. print(s1) # GET
    5. # 转换为小写
    6. s2 = s.lower()
    7. print(s2) # get
  • startswith 开始处包含

  • endswith 结束处包含

    1. s = '分享 1111111111111'
    2. # 判断字符串开头文本
    3. b1 = s.startswith('分享')
    4. print(b1)
    5. # 判断字符串结尾字符
    6. b2 = s.endswith('111')
    7. print(b2)
  • strip 去除空格

  • lstrip 去除左边空格
  • rstrip 去除右边空格

    1. s = ' python '
    2. # 去掉两边的空格
    3. s1 = s.strip()
    4. print(s1,len(s1),len(s))
    5. # 去除左边的空格
    6. s2 = s.lstrip()
    7. print(s2,len(s2),len(s))
    8. # 去除右边的空格
    9. s3 = s.rstrip()
    10. print(s3,len(s3),len(s))
    1. python 6 15
    2. python 12 15
    3. python 9 15
  • replace 文本替换

    1. s = 'helloworld'
    2. s1 = s.replace('world','china')
    3. print(s1) #hellochina
  • join

    1. >>> n = ['a','b','c']
    2. >>> str(n)
    3. "['a', 'b', 'c']"
    4. >>> n1 = str(n)
    5. >>> n1[0]
    6. '['
    7. >>> n1[1]
    8. "'"
    9. >>> n1[2]
    10. 'a'
    11. >>> n1[3]
    12. "'"
    13. >>> n1[4]
    14. ','
    15. >>> ''.join(n) #列表转换为字符串
    16. 'abc'
    17. >>>

    更多关于字符串的方法
    https://docs.python.org/zh-cn/3/library/stdtypes.html#string-methods

list 列表的常用方法

  • append 追加元素list 的末尾

    1. students = ['xiaoming','xiaowang']
    2. # 添加元素到list末尾
    3. students.append('xiaoli')
    4. print(students) # ['xiaoming', 'xiaowang', 'xiaoli']
  • insert 插入元素到指定位置

    1. students = ['xiaoming','xiaowang']
    2. students.insert(0,'xiaohua')
    3. print(students) # ['xiaohua', 'xiaoming', 'xiaowang']
  • 修改list中元素值,通过访问索引位置来修改 ```python students = [‘xiaoming’,’xiaowang’] students[0] = “xiaofang” print(students) #[‘xiaofang’, ‘xiaowang’]

  1. - pop 删除
  2. ```python
  3. students = ['xiaoming','xiaowang']
  4. #默认删除最后一个元素
  5. students.pop()
  6. print(students) # ['xiaoming']
  1. students = ['xiaoming','xiaowang']
  2. #传入索引值,根据索引删除元素;
  3. students.pop(0)
  4. print(students) # ['xiaowang']
  • remove 根据文本值进行删除 ```python students = [‘xiaoming’,’xiaowang’,’xiaoli’,’xiaohong’,’xiaofang’,’xiaoli’] students.remove(‘xiaoli’) # 删除符合条件的第一个; print(students) # [‘xiaoming’, ‘xiaowang’, ‘xiaohong’, ‘xiaofang’, ‘xiaoli’]

TODO 思考:如何删除上述list中所有的 ‘xiaoli’

  1. - count 出现次数
  2. ```python
  3. students = ['xiaoming','xiaowang','xiaoli','xiaohong','xiaofang','xiaoli']
  4. # 统计出现的次数
  5. count = students.count('xiaoli')
  6. print(count) # 2
  • index 查找元素所在位置 ```python students = [‘xiaoming’,’xiaowang’,’xiaoli’,’xiaohong’,’xiaofang’,’xiaoli’]

index1 = students.index(‘xiaoli’) print(index1)

指定开始搜索的索引位置

index2 = students.index(‘xiaoli’,3) print(index2)

  1. - reverse 倒序
  2. ```python
  3. students = ['xiaoming','xiaowang','xiaoli','xiaohong','xiaofang','xiaoli']
  4. # students[::-1]
  5. # 将list 倒序
  6. students.reverse()
  7. print(students)
  • sort 排序 ```python students = [‘xiaoming’,’xiaowang’,’xiaoli’,’xiaohong’,’xiaofang’,’xiaoli’]

排序 从小到大排序

students.sort() print(students) # [‘xiaofang’, ‘xiaohong’, ‘xiaoli’, ‘xiaoli’, ‘xiaoming’, ‘xiaowang’]

从大到小排序

students.sort(reverse=True) print(students) # [‘xiaowang’, ‘xiaoming’, ‘xiaoli’, ‘xiaoli’, ‘xiaohong’, ‘xiaofang’]

  1. <a name="QwH8T"></a>
  2. ### tuple 元组
  3. 一个元组由几个被逗号隔开的值组成;
  4. ```python
  5. >>> a = 1,2
  6. >>> type(a)
  7. <class 'tuple'>
  8. >>> a
  9. (1, 2)

元组支持索引,切片,步长操作;

元组中值不能修改;

  1. >>> a[1] = 3
  2. Traceback (most recent call last):
  3. File "<stdin>", line 1, in <module>
  4. TypeError: 'tuple' object does not support item assignment

元组中只有两个方法

  • index 查找索引
  • count 统计次数

list ,tuple 之间数据相互转换

  1. students = ('xiaoming','xiaowang')
  2. print(type(students))
  3. # 转换为列表
  4. slist = list(students)
  5. print(slist)
  6. # 转换为元组
  7. tlist = tuple(slist)
  8. print(tlist)

set 集合

无序(没有顺序),没有重复数据;

  1. >>> b = {1,2,3,2,2,2}
  2. >>> type(b)
  3. <class 'set'>
  4. >>> b
  5. {1, 2, 3}
  6. >>>

给定的列表nums中有很多数字,请你写段代码: 将nums中重复的数据去掉,并且按照从大到小的顺序进行排列;

  1. nums = [1,5,2,3,4,6,5,3,4,1,10,90,57,34,34,24]
  1. 先把重复数据去掉, 使用set数据特性,进行数据类型转换;

    1. >>> nums = [1,5,2,3,4,6,5,3,4,1,10,90,57,34,34,24]
    2. >>> set(nums)
    3. {1, 2, 3, 4, 5, 6, 34, 10, 24, 57, 90}
  2. 将set数据转换为list (列表)

    1. >>> numset = set(nums)
    2. >>> numset
    3. {1, 2, 3, 4, 5, 6, 34, 10, 24, 57, 90}
    4. >>> numlist = list(numset)
    5. >>> numlist
    6. [1, 2, 3, 4, 5, 6, 34, 10, 24, 57, 90]
  3. 使用list中内置的方法进行数据排序

    1. >>> numlist.sort() # 从小到大
    2. >>> numlist
    3. [1, 2, 3, 4, 5, 6, 10, 24, 34, 57, 90]
    4. >>> numlist.sort(reverse=True) # 从大到小
    5. >>> numlist
    6. [90, 57, 34, 24, 10, 6, 5, 4, 3, 2, 1]

集合的运算

  1. >>> a = set('abracadabra')
  2. >>> b = set('alacazam')
  3. >>> a # unique letters in a
  4. {'a', 'r', 'b', 'c', 'd'}
  5. >>> a - b # letters in a but not in b
  6. {'r', 'd', 'b'}
  7. >>> a | b # letters in a or b or both
  8. {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
  9. >>> a & b # letters in both a and b
  10. {'a', 'c'}
  11. >>> a ^ b # letters in a or b but not both
  12. {'r', 'd', 'b', 'm', 'z', 'l'}

dict 字典数据

理解字典的最好方式,就是将它看做是一个 键: 值 对的集合,键必须是唯一的(在一个字典中)

  1. xiaoming = {
  2. "username":"xiaoming",
  3. "age":30,
  4. "work":3,
  5. "hobby":['sports','movie']
  6. }

访问字典中某个字段值,通常使用[key]方式进行访问;

  1. print(xiaoming["username"],xiaoming['age'],xiaoming['work'])

字典,集合这两种数据结构没有顺序,不支持索引,切片和步长的操作;

字典中常用的方法

  • 添加或者修改对用的key的值 ```python xiaoming = { “username”:”xiaoming”, “age”:30, “work”:3, “hobby”:[‘sports’,’movie’] } xiaoming[‘salary’] = 10000 print(xiaoming) # {‘username’: ‘xiaoming’, ‘age’: 30, ‘work’: 3, ‘hobby’: [‘sports’, ‘movie’], ‘salary’: 10000} xiaoming[‘age’] = 25 print(xiaoming) # {‘username’: ‘xiaoming’, ‘age’: 25, ‘work’: 3, ‘hobby’: [‘sports’, ‘movie’], ‘salary’: 10000}
  1. - get 获取对应字段的value, 如果没有这个字段,返回结果为None
  2. ```python
  3. xiaoming = {
  4. "username":"xiaoming",
  5. "age":30,
  6. "work":3,
  7. "hobby":['sports','movie']
  8. }
  9. age = xiaoming.get('age')
  10. print(age) # 30
  11. aa = xiaoming.get('aaa')
  12. print(aa) # None
  • update 更新或者新增字段

    1. xiaoming = {
    2. "username":"xiaoming",
    3. "age":30,
    4. "work":3,
    5. "hobby":['sports','movie']
    6. }
    7. xiaoming.update(age=25)
    8. print(xiaoming) # {'username': 'xiaoming', 'age': 25, 'work': 3, 'hobby': ['sports', 'movie']}
    9. xiaoming.update(salary=10222)
    10. print(xiaoming) # {'username': 'xiaoming', 'age': 25, 'work': 3, 'hobby': ['sports', 'movie'], 'salary': 10222}
  • keys 获取所有key

    1. xiaoming = {
    2. "username":"xiaoming",
    3. "age":30,
    4. "work":3,
    5. "hobby":['sports','movie']
    6. }
    7. # 获取所有的key值
    8. keys = xiaoming.keys()
    9. print(keys) #dict_keys(['username', 'age', 'work', 'hobby'])
  • values 获取所有的values

    1. xiaoming = {
    2. "username":"xiaoming",
    3. "age":30,
    4. "work":3,
    5. "hobby":['sports','movie']
    6. }
    7. # 获取所有的values值
    8. values = xiaoming.values()
    9. print(values) # dict_values(['xiaoming', 30, 3, ['sports', 'movie']])
  • items 将 key,value 放在一起 ```python xiaoming = { “username”:”xiaoming”, “age”:30, “work”:3, “hobby”:[‘sports’,’movie’] }

    获取所有的values值

    items = xiaoming.items() print(items) # dict_items([(‘username’, ‘xiaoming’), (‘age’, 30), (‘work’, 3), (‘hobby’, [‘sports’, ‘movie’])])

  1. - popitem 删除最后一个字段
  2. ```python
  3. xiaoming = {
  4. "username":"xiaoming",
  5. "age":30,
  6. "work":3,
  7. "hobby":['sports','movie']
  8. }
  9. # 删除最后一个字段
  10. xiaoming.popitem()
  11. print(xiaoming) # {'username': 'xiaoming', 'age': 30, 'work': 3}
  • pop 删除指定字段 ```python xiaoming = { “username”:”xiaoming”, “age”:30, “work”:3, “hobby”:[‘sports’,’movie’] }

    删除最后一个字段

    xiaoming.pop(‘age’) print(xiaoming) # {‘username’: ‘xiaoming’, ‘work’: 3, ‘hobby’: [‘sports’, ‘movie’]}
  1. <a name="zeWA4"></a>
  2. #### 集合&字典
  3. 一对花括号可以创建一个空字典:`{}` <br />创建空的集合可以直接使用 set()
  4. ```python
  5. >>> a = {}
  6. >>> type(a)
  7. <class 'dict'>
  8. >>> b = set()
  9. >>> type(b)
  10. <class 'set'>
  11. >>>

循环 for … in …

  1. 循环字符串

    1. s = 'abcdefg'
    2. # for 变量 in 循环的对象
    3. for x in s:
    4. print(x)
  2. 循环列表 ```python students = [‘xiaoming’,’xiaowang’,’xiaozhang’,’xiaoli’] for name in students: print(f’开始注册用户{name}’) print(f’注册成功’)

  1. 3. 循环元组
  2. ```python
  3. students = 'xiaoming','xiaowang','xiaozhang','xiaoli'
  4. for name in students:
  5. print(f'开始注册用户{name}')
  6. print(f'注册成功')
  1. 循环集合 ```python students = {‘xiaoming’,’xiaowang’,’xiaozhang’,’xiaoli’} for name in students: print(f’开始注册用户{name}’) print(f’注册成功’)
  1. 5. 循环字典
  2. 默认循环循环的是字典的key
  3. ```python
  4. xiaoming = {
  5. "username":"xiaoming",
  6. "age":30,
  7. "work":3,
  8. "hobby":['sports','movie']
  9. }
  10. # 循环打印处字典的key 和 value
  11. for x in xiaoming:
  12. print(x)
  1. # 循环打印处字典的key 和 value
  2. for x in xiaoming:
  3. print(x,xiaoming[x])
  1. info=[('name','xiaohong'),('age',20)]
  2. for x,y in info:
  3. print(f'{x}={y}')
  1. xiaoming = {
  2. "username":"xiaoming",
  3. "age":30,
  4. "work":3,
  5. "hobby":['sports','movie']
  6. }
  7. print(xiaoming.items())
  8. for key,value in xiaoming.items():
  9. print(f'{key}={value}')

range 函数

range可以生成指定的循环次数

  1. for x in range(100)
  1. for i in range(3):
  2. print(f'helloword{i}')

range 函数也支持切片,步长操作;
range(start,end,step)

  1. for i in range(1,101,2):
  2. print(i)

求1-100 之和;

  1. # 1+2+3+4+5+6+...+100
  2. # 1+2 = 3
  3. # 3+3 = 6
  4. # 6+4 =10
  5. sum_i = 0
  6. for i in range(1,101):
  7. print(f'{sum_i}+{i}={sum_i+i}')
  8. sum_i = sum_i+i
  9. print(sum_i)

求1-100 奇数之和:

  1. sum_i = 0
  2. for i in range(1,101,2):
  3. print(f'{sum_i}+{i}={sum_i+i}')
  4. sum_i = sum_i+i
  5. print(sum_i)

while 循环

  1. while 表达式:
  2. 执行体

死循环

  1. while True:
  2. print('helloworld')

使用while循环计算 1-100 之和

  1. counter = 1
  2. sum = 0
  3. while counter < 101:
  4. print(f'{sum}+{counter}={sum+counter}')
  5. sum = sum+counter
  6. counter = counter + 1
  7. print(sum)

break

跳出循环

  1. for x in range(10):
  2. print('hahahahaha')
  3. if x == 3:
  4. break
  1. i = 0
  2. while True:
  3. print('hahah')
  4. i+=1 # i = i+1
  5. if i == 3:
  6. break

continue

继续从头开始操作,不中断整个循环

  1. for x in range(10):
  2. print(f'开始执行{x}')
  3. if x==3 or x ==6:
  4. continue
  5. print(f'结束执行{x}')
  1. x = 0
  2. while x < 10:
  3. x += 1
  4. print(f'开始执行 {x}')
  5. if x == 3 or x == 6:
  6. continue
  7. print(f'结束执行 {x}')

if … elif … else 条件判断语句

基本使用

  1. if 条件判断语句:
  2. 执行体A
  3. else:
  4. 执行体B

条件判断语句的结果为 True的时候, 自动执行 执行体A,结束条件判断
否则执行执行体B

  1. a = 4
  2. if a>5 :
  3. print("大")
  4. else:
  5. print('小')
  1. """
  2. 当成绩 在0-59 评 差
  3. 成绩在 60-80 评 良
  4. 80-100 评 优
  5. """
  6. score = 85.5
  7. if score >=0 and score <= 59:
  8. print('差')
  9. elif score >=60 and score <=79 :
  10. print('良')
  11. elif score>=80 and score <=100:
  12. print('优')
  13. else: # 如果以上条件都不符合
  14. print('成绩不合法')

总结

2.Python数据类型 list,tuple,set,dict - 图2

参考资料

https://docs.python.org/zh-cn/3/tutorial/controlflow.html