- 官方手册
- 菜鸟站手册地址:
- python的运行方法
- 注释
- 小技巧:
- input()接收用户输入的内容(默认为字符串)
- print()
- 运算符
- is 是判断两个标识符是不是引用自一个对象
- all和any
- 强制类型转换
- type()
- float()
- str()
- int()
- 字符串和字节的转换
- 数组和字符串互转
- 标准数据类型
- 判断数据类型
- 列表 集合 元组 字典 的特性介绍
- 各种数据结构的各种操作
- 变量
- 字符串
- 字符串的拼接
- 字符串的重复输出
- 字符串的换行
- 字符串的不换行
- 字符串for循环
- format() 格式化方法
- f格式化
- %格式化
- 格式化总结
- 转义字符
- 列表 (相当于PHP里的索引数组)
- 列表的添加
- 列表的删除
- 列表的更新 指定列表里元素的索引下标重新赋值
- 列表截取(切片)与拼接
- 嵌套列表
- 重复
- 列表的赋值
- 列表去重
- 排序
- 排序 正序 ,注意这里会修改list1原列表
- 倒序
- 交集、差集、并集
- 元组
- 序列
- 字典
- 为什么需要字典:
- 创建字典:
- 基本操作:
- 字典常用方法:
- 遍历字典:
- 直接赋值和 copy 的区别
- 浅拷贝和深拷贝的区别
- 函数
- 循环
- for循环
- while循环
range()函数循环列表- 判断if..elif..else
break与continue的区别- 数据的推导式
- 拆包
- 函数
官方手册
https://docs.python.org/3.7/tutorial/index.html
菜鸟站手册地址:
https://www.runoob.com/python3/python3-basic-operators.html
python的运行方法
- Sublime编辑器执行python代码,用Ctrl+b
- cmd黑窗口里 D:\phpStudy\PHPTutorial\WWW\python>python test.py
注释
确保对模块, 函数, 方法和行内注释使用正确的风格
Python中的注释有单行注释和多行注释:
Python中单行注释以 # 开头,例如:
三个单引号,或者三个双引号
'''这是一个区块连的函数,
money:交易的金额
last_value 获取到数组的最后一个单元(默认值为[1])
Docstring'''参考手册:
https://www.runoob.com/python3/python3-comment.html
小技巧:
input()接收用户输入的内容(默认为字符串)
amount = float(input(‘请输入金额: ‘))
print()
打印输出
由于我们正在讨论格式问题,就要注意 print 总是会以一个不可见的“新一行”字符(\n)结尾,因此重复调用 print将会在相互独立的一行中分别打印。为防止打印过程中出现这一换行符,你可以通过 end 指定其应以空白结尾:
print('a', end='')
print('b', end='')输出结果如下:
ab
或者你通过 end 指定以空格结尾:
print('a', end=' ')
print('b', end=' ')
print('c')输出结果如下:
a b c
字符串拼接变量的输出
str2=2 + 3 * 4
a1 ='str 的值是' + str(str2)
a1 ='str 的值是' + str2 #报错,字符串不和字数拼接
print (a1) #str 的值是14
print ('str 的值是' ,str2) #str 的值是 14运算符
is 是判断两个标识符是不是引用自一个对象
a = [20,30]
b = [20,30]
c = a
if ( a is b ):
print ("1 - a 和 b 有相同的标识")
else:
print ("1 - a 和 b 没有相同的标识")
if ( a is c ):
print ("5 - a 和 c 有相同的标识")
else:
print ("5 - a 和 c 没有相同的标识")
if ( id(a) == id(b) ):
print ("2 - a 和 b 有相同的标识")
else:
print ("2 - a 和 b 没有相同的标识")
# 修改变量 b 的值
b = 30
if ( a is b ):
print ("3 - a 和 b 有相同的标识")
else:
print ("3 - a 和 b 没有相同的标识")
if ( a is not b ):
print ("4 - a 和 b 没有相同的标识")
else:
print ("4 - a 和 b 有相同的标识")输出:
1 - a 和 b 没有相同的标识
5 - a 和 c 有相同的标识
2 - a 和 b 没有相同的标识
3 - a 和 b 没有相同的标识
4 - a 和 b 没有相同的标识https://www.runoob.com/python3/python3-basic-operators.html
all和any
- all相当于and并且
- any相当于or或者
test_list = [1,2,3,4,-5] test = [el > 0 for el in test_list] #[True, True, True, True, False] print(all(test)) #False print(any(test)) #True
强制类型转换
type()
打印数值类型
float()
将字符串的数字转为浮点型
str()
将数字转为字符串
int()
将浮点型转为整型
a = 12.5
a = int(12.5)
print(a) #输出:12 向下取整字符串和字节的转换
# 字符串转字节串
text = "hello python"
b1 = text.encode(encoding='utf-8')
print(b1) # b'hello python'
# 字节转字符串
bStr = b1.decode(encoding='utf-8')
print(bStr) # hello python'
数组和字符串互转
list1 = ['red', 'green', 'blue', 'yellow', 'white', 'black']
list1_str = ','.join(list1)
print("list_to_str:", list1_str) # list_to_str: red,green,blue,yellow,white,black
list_arr = list1_str.split(',')
print("list_arr:", list_arr) # list_arr: ['red', 'green', 'blue', 'yellow', 'white', 'black']标准数据类型
Python3 中有六个标准的数据类型:
Number(数字)
String(字符串)
List(列表)
Tuple(元组)
Set(集合)
Dictionary(字典)
Python3 的六个标准数据类型中:
不可变数据(3 个):Number(数字)、String(字符串)、Tuple(元组)。 # 数字无
可变数据(3 个):List(列表)、Dictionary(字典)、Set(集合)。 # 列字集类型可以看成一个对象.help() 后连按加回车 可以查看类型下面的函数
如:
- help(str)
- help(list)
判断数据类型
a = {1,2}
# if isinstance(a,str):
# if isinstance(a,int):
# if isinstance(a,list):
if isinstance(a,):
print(True)
else:
print(False)列表 集合 元组 字典 的特性介绍
# animal = ['pig','dog','cat','dog','pig'] #列表
# animal = {'pig','dog','cat','dog','pig'} #集合
# animal = ('pig','dog','cat','dog','pig') #元组
# animal = {'name':'lisi','age':28,'weight':120} #字典| 类型 | 特性 | 符号 |
|---|---|---|
| 列表 | 可编辑 有序 允许重复 | [] |
| 集合 | 可编辑 无序 不可重复 | {} |
| 元组 | 不可编辑 有序 可重复 | () |
| 字典 | 无序 可编辑 值:可重复 键:不可重复 键值对形式 | {} |
各种数据结构的各种操作
| 类型 | 列表推导 | for循环 | 索引 | 拆包 | 符号 |
|---|---|---|---|---|---|
| 列表 | 可以 | 可以 | 可以 | 可以 | [] |
| 集合 | 可以 | 可以 | 不可以 | 可以 | {} |
| 元组 | 可以 | 可以 | 可以 | 可以 | () |
| 字典 | 可以 | 可以 | 可以 | 可以 | {} |
变量
- 变量可以理解为一个空盒子,向变量赋值可以理解为向空盒子子里存东西,向变量重新赋值可以理解为把盒子里原有的东西拿出来,放入新的东西
- 声明变量前不需加任何声明.php前需要加$,JavaScript前需要加var,python不需要
- 变量分为
局部变量和全局变量,局部变量可以通过global转为全局变量

#变量的赋值(也叫拆包)
list = ('wangwu',28)
name,age=list
print(name,age) #wangwu 28
#定义global全局变量
name = 'lisi'
def get_name():
global name
name = input('please input your are name:')
get_name() #运行函数局部变量就会通过global转为全局变量
print(name) #输出的是input里您输入的值字符串
字符串的拼接
a= 'hello'
b='word'
c = a + b
print ("值为:", c) # 'helloword'字符串的重复输出
str='la' * 3
print (str) #lalala字符串的换行
方法一.用三个单引号或者三个双引号
str= '''asdfasdfasdf
asdfasdfasdfdfasdf
asdfasdfasdfdfasdf
'''
print (str)输出
asdfasdfasdf
asdfasdfasdfdfasdf
asdfasdfasdfdfasdf方法二.用\n符号换行
'This is the first line\nThis is the second line'输出
This is the first line
This is the second line字符串的不换行
str= "This is the first sentence. \
This is the second sentence."
print (str)输出
This is the first sentence. This is the second sentence.字符串for循环
st = 'abcdefg'
for s in st :
print(s)输出:
a
b
c
d
e
f
gformat() 格式化方法
name = 'lisi'
age = '28'
# new_str = 'I am '+ name +' and I am '+ age +' years old.'
# new_str = 'I am {} and I am {} years old.'.format(name, age)
# new_str = 'I am {0} and I am {1} years old. I like my name {0}'.format(name, age) #用索引可以重复调用
# new_str = 'I am {name} and I am {age} years old.' #变量不会解析
# new_str = 'I am {name} and I am {age} years old.'.format(name = name, age = age)
# print(new_str)
funds = 123.456
# new_str = 'Funds: {0:f}'.format(funds)
# <:居右 >:居左 ^:居中 0是点位符,冒号后面的是要输出的符号, 10是共计输出多少位,
# f是转为浮点数(默认保留小数点后四位),f前可以指定小数点后保留多少位,
new_str2 = 'Funds:|{0:-^10.2f}|'.format(funds)
print(new_str2) #Funds:|--123.46--|
print(f"{'lisi':-^20}") #--------lisi--------
更多例子:
https://bop.mol.uno/07.basics.html
f格式化
name ='tongpan'
# age = 28
# person = {'name':'tongpan', 'age':28}
# new_str = f"I am {person['name']} and I am {person['age']+2} years old."
# <:居右 >:居左 ^:居中 0是点位符,冒号后面的是要输出的符号, 10是共计输出多少位,
# f是转为浮点数(默认保留小数点后四位),f前可以指定小数点后保留多少位,
# new_str = f"|{name:-^20}|" #|------tongpan-------|
# new_str = f"|{name:->20}|" #|-------------tongpan|
new_str = f"|{name:-<20}|" #|tongpan-------------|
# pi = 3.1415926
# new_str = f"{pi:.3f}" # 3.142 保留三位小数,四舍五入
print(new_str)%格式化
打印单个变量
# 整形:%d # 字符串类型:%s # 浮点类型: %f (几位小数就写几f 如:12.45 %2f) # 字符串变量类型的格式化 name = 'zhiliao' print('my name is %s'%name) # 整形变量的格式化 age = 2147483648 print('my age is %d'%age) # 浮点类型变量的格式化 price = 18.9 print("apple's price is %f"%price) print("apple's price is %.2f"%price)打印多个变量
name = 'zhiliao' age = 18 gender = 'boy' # 元组 print('my name is %s,my age is %d,gender is %s'% (name,age,gender))其他打印方式:
# 如果想字符串的末尾打印一个变量,那么可以采用以下方式 age = 18 print('my age is',age) # 如果是其他数据类型,使用%s的方式进行格式化 # 那么其实,Python是首先将这个数据转换为字符串 # 再进行格式化。 age = 18 print('my age is %s'%age)
格式化总结
name = 'lisi'
age = 20
gender = '男'
# str1 = 'my name is %s,age is %d,gender is %s'% (name,age,gender) #my name is lisi,age is 20,gender is 男
# str1 = 'my name is {},age is {},gender is {}'.format(name,age,gender) #my name is lisi,age is 20,gender is 男
str1 = f'my name is {name},age is {age},gender is {gender}' #my name is lisi,age is 20,gender is 男
print(str1)
info = {}
info['name']=name
info['age']=age
info['gender']=gender
# str2 = 'my name is %s,age is %d,gender is %s'% (info['name'],info['age'],info['gender']) #my name is lisi,age is 20,gender is 男
# str2 = 'my name is {},age is {},gender is {}'.format(info['name'],info['age'],info['gender']) #my name is lisi,age is 20,gender is 男
str2 = f"my name is {info['name']},age is {info['name']},gender is {info['gender']}" #my name is lisi,age is 20,gender is 男
print(str2)
print(info['name']) #lisi
print(info['age']) #20
# print(info['color']) #20 报异常转义字符
new_str = '\I\m tongp\a\n'
'
"
\
\n
\a
\t
\b
\f
\N
\v
\ooo
\xhh
\Uxxxxxx
\uxxxx
print(new_str)手册:
列表 (相当于PHP里的索引数组)
参考菜鸟手册
https://www.runoob.com/python3/python3-list.html
- 相当里php里的数组
- 序列中的每个元素都分配一个数字 - 它的位置(索引),第一个索引是0,第二个索引是1,依此类推。
list1 = ['Google', 'Runoob', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print ("list1[0]: ", list1[0]) #list1[0]: Google
print ("list2[1:5]: ", list2[1:5]) #list2[1:5]: [2, 3, 4, 5]列表的添加
列表相当于php中的一维数组,里面元素是有序的,可以重复的.
- 向列表的最后面追加单元数据
列表的追加(向数组的右边追加) append()方法
list1 = ['Google', 'Runoob', 'Taobao']
list1.append('Baidu')
print ("更新后的列表 : ", list1) #['Google', 'Runoob', 'Taobao', 'Baidu']向数组后面拼接元素
list1 = ['Google', 'Runoob', 'Taobao'] n = ['a','b','c'] list1 += n print(list1) #['Google', 'Runoob', 'Taobao', 'a', 'b', 'c']insert()函数用于向列表指点任意列表的插入值。insert()方法list.insert(index, obj)
list1 = ['Google', 'Runoob', 'Taobao']
list1.insert(1, 'Baidu')
print ('列表插入元素后为 : ', list1) #['Google', 'baidu', 'Runoob', 'Taobao']extend()函数用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)。
extend()方法语法:
list.extend(seq)
list1 = ['Google', 'Runoob', 'Taobao']
list2=list(range(5)) # 创建 0-4 的列表
list1.extend(list2) # 扩展列表
print ("扩展后的列表:", list1) # ['Google', 'Runoob', 'Taobao', 0, 1, 2, 3, 4]5.extend 与 append 的区别
- extend 与 append 方法的相似之处在于都是将新接收到参数放置到已有列表的后面。
- 而 extend 方法只能接收 list,且把这个 list 中的每个元素添加到原 list 中。
- 而 append 方法可以接收任意数据类型的参数,并且简单地追加到 list 尾部。
list1 = ['Google', 'Runoob', 'Taobao']
list1.extend(['a','b']) # 扩展列表
print (list1) # ['Google', 'Runoob', 'Taobao', 'a', 'b']
list2 = ['Google', 'Runoob', 'Taobao']
list2.append(['a','b']) # 扩展列表
print (list2) # ['Google', 'Runoob', 'Taobao', ['a', 'b']]https://www.runoob.com/python3/python3-att-list-extend.html
列表的删除
方法一:可以使用 del 语句来删除列表的指定元素,如下实例:
list = ['Google', 'Runoob', 1997, 2000]
print ("原始列表 : ", list) #原始列表 : ['Google', 'Runoob', 1997, 2000]
del list[2]
print ("删除第三个元素 : ", list) #删除第三个元素 : ['Google', 'Runoob', 2000]方法二:
remove()
描述
remove() 函数用于移除列表中某个值的第一个匹配项。
语法
remove()方法语法:list.remove(obj)
list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list1.remove('Taobao')
print ("列表现在为 : ", list1) #列表现在为 : ['Google', 'Runoob', 'Baidu']
list1.remove('Baidu')
print ("列表现在为 : ", list1) #列表现在为 : ['Google', 'Runoob']方法三:pop(列表索引)
描述
pop(列表索引) 函数用于移除列表中某索引的值
不列索引,默认删除最后一个元素
list = ['Google', 'Runoob', 1997, 2000]
list.pop(2)
print(list) #['Google', 'Runoob', 2000]列表的更新 指定列表里元素的索引下标重新赋值
你可以对列表的数据项进行修改或更新,如下所示:
指定列表里元素的索引下标重新赋值
list = ['Google', 'Runoob', 1997, 2000]
print ("第三个元素为 : ", list[2]) #第三个元素为 : 1997
list[2] = 2001
print ("更新后的第三个元素为 : ", list[2]) #更新后的第三个元素为 : 2001列表截取(切片)与拼接
Python的列表截取与字符串操作类型.
如下所示:
L=[‘Google’, ‘Runoob’, ‘Taobao’]
| Python 表达式 | 结果 | 描述 |
|---|---|---|
| L[2] | ‘Taobao’ | 读取第三个元素 |
| L[-2] | Runoob’ | 从右侧开始读取倒数第二个元素: count from the right |
| L[1:] | [‘Runoob’, ‘Taobao’] | 输出从第二个元素开始后的所有元素 |
| L[:] | [‘Google’, ‘Runoob’, ‘Taobao’] | 输出所有元素 |
组合
list1 = ['Google', 'Runoob', 'Taobao']
n = ['a','b','c']
list1 += n
# 或者
list = list+n
print(list1) #['Google', 'Runoob', 'Taobao', 'a', 'b', 'c']嵌套列表
把两个一维列表嵌套成一个两维列表
a = ['Google', 'Runoob', 'Taobao'] b = ['a','b','c'] c = [a,b] print(c) #[['Google', 'Runoob', 'Taobao'], ['a', 'b', 'c']]
重复
print(['Hi!'] * 4) # ['Hi!', 'Hi!', 'Hi!', 'Hi!']列表的赋值
copy()和直接=赋值的区别:
- 使用=直接赋值,是引用赋值,更改一个,另一个同样会变
- copy() 则顾名思义,复制一个副本,原值和新复制的变量互不影响
例子:
https://www.runoob.com/python3/python3-att-list-copy.html
# 列表的传值赋值 (原列表a数据值改变,不影响赋值的新列表b)
a=[0,1,2,3,4,5]
# 列表的传值赋值的几种方法
b=a.copy() #copy()函数传值赋值
# b=a[:] #切片传值赋值
b=a[0:] #切片传值赋值
a[0] = 6
print(a) #[6, 1, 2, 3, 4, 5]
print(b) #[0, 1, 2, 3, 4, 5]
# 列表的引用赋值 (原列表a和新列表c指的是同一个列表在内存里的地址,可以理解为同一个列表起的不同的别名)
# 原列表c数据值改变,新列表b的值也改变
c=[0,1,2,3,4,5]
d=c
c[0] = 6
print(c) #[6, 1, 2, 3, 4, 5]
print(d) #[6, 1, 2, 3, 4, 5]列表去重
list1 = ['Google', 'Runoob', 'Taobao', 'Taobao']
# 原理:字典的键不允许重复,因此可以自动去重;Python
# 3.7 + 中字典键默认保持插入顺序。
unique_list = list(dict.fromkeys(list1))
print(unique_list) # 输出: ['Google', 'Runoob', 'Taobao']
# 列表转为集合(此时会 无序 去重复),再转回列表 达到去重的目的
list1 = ['black', 'yellow','apple','apple']
print(list(set(list1))) # 输出:['apple', 'yellow', 'black']排序
一维列表
`python
list1 = [‘black’, ‘yellow’, ‘apple’]排序 正序 ,注意这里会修改list1原列表
sorted(list1)
print(list1) # output: [‘apple’, ‘black’, ‘yellow’]list1.reverse() # 反转列表
print(list1) # output: [‘yellow’, ‘black’, ‘apple’]倒序
sorted(list1, reverse=True)
print(list1) # output: [‘yellow’, ‘black’, ‘apple’]
2. 二维列表
```python
def takeSecond(elem):
return elem[1]
def takeIndex(index):
def key_func(elem):
return elem[index]
return key_func
def print_hi(name):
# 获取列表的第二个元素
# 列表
random = [[2, 2], [3, 4], [4, 1], [1, 3]]
# 指定第二个元素排序
random.sort(key=takeSecond)
# 输出类别
print('排序列表:', random) # [[4, 1], [2, 2], [1, 3], [3, 4]]
# 指定第N个元素排序
random.sort(key=takeIndex(0))
# 输出类别
print('排序列表:', random) # [[1, 3], [2, 2], [3, 4], [4, 1]]
- 列表嵌套对象排序
# 列表
random = [
{'name': 'lisi', 'age': 19},
{'name': 'zhangsan', 'age': 23},
{'name': 'wangwu', 'age': 18}
]
# 按age 正序排序 不会修改原始列表
sorted_list_asc = sorted(random, key=lambda x: x["age"])
print(random)
# 输出原始列表 [{'name': 'lisi', 'age': 19}, {'name': 'zhangsan', 'age': 23}, {'name': 'wangwu', 'age': 18}]
print(sorted_list_asc)
# 输出排序后的列表 [{'name': 'wangwu', 'age': 18}, {'name': 'lisi', 'age': 19}, {'name': 'zhangsan', 'age': 23}]
# 按age 倒序排序
sorted_list_desc = sorted(random, key=lambda x: x["age"], reverse=True)
print(sorted_list_desc)
# 输出排序后的列表 [{'name': 'zhangsan', 'age': 23}, {'name': 'wangwu', 'age': 18}, {'name': 'lisi', 'age': 19}]
# 按name 正序排序
sorted_list_asc = sorted(random, key=lambda x: x["name"])
print(sorted_list_asc)
#[{'name': 'lisi', 'age': 19}, {'name': 'wangwu', 'age': 18}, {'name': 'zhangsan', 'age': 23}]
交集、差集、并集
list1 = ['black', 'yellow','apple','apple']
list2 = ['blue', 'yellow', 'apple']
# 求 list1 不在 list2 中的数据
print(list(set(list1).difference(set(list2)))) # output ['black']
# 求 list1 和 list2 的交集
print(list(set(list1).intersection(set(list2)))) # output ['yellow', 'apple']
# 求 list1 和 list2 的并集
print(list(set(list1).union(set(list2)))) # output ['black', 'yellow', 'apple', 'blue']
# 求 list1 和 list2 都不在对方列表中的数据
print(list(set(list1).symmetric_difference(set(list2)))) # output ['black', 'blue']
元组
Python 的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号,列表使用方括号。
相同之处,它们的元素都是有序的,可以重复的
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
手册:
https://www.runoob.com/python3/python3-tuple.html
序列
列表、元组和字符串可以看作序列(Sequence)的某种表现形式,可是究竟什么是序列,它又有什么特别之处?
序列的主要功能是资格测试(Membership Test)(也就是 in 与 not in 表达式)和索引操作(Indexing Operations),它们能够允许我们直接获取序列中的特定项目。
上面所提到的序列的三种形态——列表、元组与字符串,同样拥有一种切片(Slicing)运算符,它能够允许我们序列中的某段切片——也就是序列之中的一部分。
案例(保存为 ds_seq.py):
shoplist = ['apple', 'mango', 'carrot', 'banana']
name = 'swaroop'
# Indexing or 'Subscription' operation #
# 索引或“下标(Subscription)”操作符 #
print('Item 0 is', shoplist[0])
print('Item 1 is', shoplist[1])
print('Item 2 is', shoplist[2])
print('Item 3 is', shoplist[3])
print('Item -1 is', shoplist[-1])
print('Item -2 is', shoplist[-2])
print('Character 0 is', name[0])
# Slicing on a list #
print('Item 1 to 3 is', shoplist[1:3])
print('Item 2 to end is', shoplist[2:])
print('Item 1 to -1 is', shoplist[1:-1])
print('Item start to end is', shoplist[:])
# 从某一字符串中切片 #
print('characters 1 to 3 is', name[1:3])
print('characters 2 to end is', name[2:])
print('characters 1 to -1 is', name[1:-1])
print('characters start to end is', name[:])输出:
Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana
Item -2 is carrot
Character 0 is s
Item 1 to 3 is ['mango', 'carrot']
Item 2 to end is ['carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop手册:
https://bop.mol.uno/12.data_structures.html
字典
为什么需要字典:
有时候我们需要存储一组相关的数据的时候,
比如要存储一个人的信息,那么有username,age,birthday等,
如果这些信息都存储在列表中,或者数组中,
比如[‘username’,’age’,’birthday’]那么用起来可能不是很方便。
比较方便的操作是,我直接通过username这个key就可以拿到这个值,
我通过username就可以给这个key设置值,
那么就可以通过字典的方式实现我们的需求。
字典 可以理解为键值对形式的json格式字符串形式 或者 php中的关联数组
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,
格式如下所示:
d = {key1 : value1, key2 : value2 }
字典是另一种可变容器模型,且可存储任意类型对象。
键必须是唯一的,但值则重复。
值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
元素是无序的
一个简单的字典实例:
dict = {‘Alice’: ‘2341’, ‘Beth’: ‘9102’, ‘Cecil’: ‘3258’}
创建字典:
#方法一:
dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };
#方法二:
info = {}
info['name']=name
info['age']=age
info['gender']=gender
#输出
print(info) #{'name': 'lisi', 'age': 20, 'gender': '男'}
print(info['name']) #lisi
print(info['age']) #20
# print(info['color']) #20 报异常
# 也可以指定一个,在没有获取到这个值时候的默认值
print(info.get('color','red')) #red
方法三:使用dict函数:
person = dict(username='zhiliao',age=18) #{'username': 'zhiliao', 'age': 18}
print(person)基本操作:
- len(d):返回字典的键值对的长度。
- d[k]:获取k这个key对应的值。
- d[k] = v:设置键为k的值为v,如果字典中不存在键为k的这一项,那么自动的添加进去。
- del d[k]:删除d这个字典中键为k的这一项数据。
- k in d:检查d这个字典中是否包含键为k的这一项。
- 字典中的键可以是任意的不可变类型,比如:浮点类型、整形、长整形、字符串或者元组。
字典常用方法:
clear:清除字典中所有的项。
a = {'username':'zhiliao','age':18} print(a) #{'username': 'zhiliao', 'age': 18} a.clear() print(a) #{}get:访问字典中那个键对应的那个值。这个方法不会抛出异常。
a = {'username':'zhiliao','age':18} username = a.get('username') print(username) #print(city) city = a.get('city') # 获取到的是一个None。 print(city) #None # 也可以指定一个,在没有获取到这个值时候的默认值 city = a.get('city','changsha') print(city) #changsha # city = a['city'] # print(city) # 抛出异常pop:用来获得对应于给定键的值,然后将这个键和值的项从字典中删除。会返回这个值。
d = {'x':1,'y':2} b=d.pop('x') print(b) # 1 print(d) # {'y': 2}popitem:随机的移除字典中的一项。因为字典是无序的,所以是随机的。
d= {'name': '菜鸟教程', 'alexa': 10000, 'url': 'www.runoob.com'} a=d.popitem() # 随机弹出一个值 print(d) # {'name': '菜鸟教程', 'alexa': 10000} print(a) #('url', 'www.runoob.com')update:用一个字典更新另外一个字典,如果碰到相同的键,则会覆盖。
a = {'url':'http://www.baidu.com/','title':"baidu"} b = {"url":"http://www.google.com/",'new_value':"new_value"} a.update(b) print(a) #{'url': 'http://www.google.com/', 'title': 'baidu', 'new_value': 'new_value'}setdefault:如果字典中包含有给定键,则返回该键对应的值,否则返回为该键设置的值。
key in dict
if k in dict:判断某个键是否在字典中存在。dict = {'Name': 'Runoob', 'Age': 7} # 检测键 Age 是否存在 if 'Age' in dict: print("键 Age 存在") else : print("键 Age 不存在") # 检测键 Sex 是否存在 if 'Sex' in dict: print("键 Sex 存在") else : print("键 Sex 不存在") # not in # 检测键 Age 是否存在 if 'Age' not in dict: print("键 Age 不存在") else : print("键 Age 存在") # 以上实例输出结果为: # 键 Age 存在 # 键 Sex 不存在 # 键 Age 存在字典k,v交换值
regions_map = { "BeiJing": "北京", "ShangHai": "上海", "TianJin": "天津", "ChongQing": "重庆", "HK": "香港", "MO": "澳门", "AnHui": "安徽", "FuJian": "福建", "GuangDong": "广东", "GuangXi": "广西", "GuiZhou": "贵州", "GanSu": "甘肃", "HaiNan": "海南", "HeBei": "河北", "HeNan": "河南", "HeiLongJiang": "黑龙", "HuBei": "湖北", "HuNan": "湖南", "JiLin": "吉林", "JiangSu": "江苏", "JiangXi": "江西", "LiaoNing": "辽宁", "Inner Mongolia Autonomous Region": "内蒙", "Ningxia Hui Autonomous Region": "宁夏", "QingHai": "青海", "Shaanxi": "陕西", "Shanxi": "山西", "ShanDong": "山东", "SiChuan": "四川", "TW": "台湾", "Tibet": "西藏", "Xinjiang": "新疆", "YunNan": "云南", "ZheJiang": "浙江" } dict2 = {value: key for key, value in regions_map.items()} print(dict2) print("get keys:", dict2.keys()) print("get values:", dict2.values())
遍历字典:
- 遍历字典中所有的key:使用keys方法,这个方法将所有的键以列表的方式返回。
a = {"url":"www.baidu.com",'title':"baidu"} for x in a.keys(): print x - 遍历字典中所有的key:使用iterkeys方法,这个方法将返回一个迭代器,用来遍历所有的键的。
a = {"url":"www.baidu.com",'title':"baidu"} for x in a.iterkeys(): print x - 遍历字典中所有的value:使用values方法,这个方法将所有的值以列表的方式返回。
a = {"url":"www.baidu.com",'title':"baidu"} for x in a.values(): print x - 遍历字典中所有的value:使用itervalues方法,这个方法将返回一个迭代器,用来遍历所有的值。
a = {"url":"www.baidu.com",'title':"baidu"} for x in a.itervalues(): print x - 遍历字典中所有的键值对:使用items方法,这个方法将所有的键和值以列表的方式返回。
a = {"url":"www.baidu.com",'title':"baidu"} for key,value in a.items(): print key print value - 遍历字典中所有的键值对:使用iteritems方法,这个方法将返回一个迭代器,用来遍历所有的键和值。
a = {"url":"www.baidu.com",'title':"baidu"} for key,value in a.iteritems(): print key print value
手册:
https://www.runoob.com/python3/python3-dictionary.html
直接赋值和 copy 的区别
可以通过以下实例说明:
dict1 = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
dict2 = dict1.copy()
print ("新复制的字典为 : ",dict2) #新复制的字典为 : {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
dict1 = {'user':'runoob','num':[1,2,3]}
dict2 = dict1 # 浅拷贝: 引用对象
dict3 = dict1.copy() # 浅拷贝:深拷贝父对象(一级目录),子对象(二级目录)不拷贝,还是引用
# 修改 data 数据
dict1['user']='root'
dict1['num'].remove(1)
# 输出结果
print(dict1) #{'user': 'root', 'num': [2, 3]}
print(dict2) #{'user': 'root', 'num': [2, 3]}
print(dict3) #{'user': 'runoob', 'num': [2, 3]}浅拷贝和深拷贝的区别
https://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html
函数
def 自定义一函数
def test():
print('My name is haima')
test() #My name is haima详情:
https://bop.mol.uno/10.functions.html
https://www.runoob.com/python3/python3-function.html
循环
for循环
blockchian = [[[1], 12.0], [[[1], 12.0], 13.0], [[[[1], 12.0], 13.0], 14.0]]
for block in blockchian:
'''这是一个区块连的函数,
money:交易的金额
last_value 获取到数组的最后一个单元(默认值为[1])
Docstring'''
print(block)while循环
while True:
print('请输入数字:')
print('1:继续交易')
print('2:打印当前区块链')
print('q:退出当前操作')
userChoice_num = get_userChoice_num()
if userChoice_num == '1':
money = get_input_money()
add_value(money,get_last_value())
elif userChoice_num == '2':
print_blockchian()
elif userChoice_num == 'q':
break #continue
else:
print('请输入列表里的数字!')range()函数循环列表
也可以使range以指定数字开始并指定不同的增量(甚至可以是负数,有时这也叫做’步长’):
for i in range(0, 10, 3) :
print(i)打印结果:
0
3
6
9手册参考
https://www.runoob.com/python3/python3-loop.html
判断if..elif..else
```python
if userChoice_num == '1':
money = get_input_money()
add_value(money,get_last_value())
elif userChoice_num == '2':
print_blockchian()
elif userChoice_num == 'q':
break #continue
else:
print('请输入列表里的数字!')
value = int(input('请输入你的值,输入整形:'))
if value == 1:
print('今天是星期一')
elif value == 2:
print('今天是星期二')
elif value == 3:
print('今天是星期三')
elif value == 4:
print('今天是星期四')
elif value == 5:
print('今天是星期五')
elif value == 6:
print('今天是星期六')
elif value == 7:
print('今天是星期日')
else:
print('请输入1-7的整数')
```手册参考
https://www.runoob.com/python3/python3-conditional-statements.html
break与continue的区别
break终止本次循环continue跳过当前操作,执行下一次循环
数据的推导式
例子一:
list = [1,2,3,4,5]
newlist = [li*2 for li in list]
print(newlist) #[2, 4, 6, 8, 10]
#加if条件筛选出符合条件的元素再做操作
list = [1,2,3,4,5]
newlist = [li*2 for li in list if li % 2==0]
print(newlist) #[4, 8]
list = [1,2,3,4,5]
items = [1,3]
newlist = [el*2 for el in list if el in items]
print(newlist) #[2, 6]
numb = [1, 2, 3, 4, 5, 6, 7]
num = '-'.join([str(v*2) for v in numb]) #join是把列表数组里的每一个值循环出来,用-号连接转为字符串
print(num) #输出:2-4-6-8-10-12-14例子二:
字典的列表推导
方法一(只能拿到键):
animal = {'name':'tongpan', 'age':28, 'weight':120}
print([el for el in animal]) #['name', 'age', 'weight']
方法二(键,值都能拿到):
animal = {'name':'tongpan', 'age':28, 'weight':120}
a = animal.items() #items把字典转为这种形式dict_items([('name', 'tongpan'), ('age', 28), ('weight', 120)])
for k,v in a:
print(k,v)
print('---------------------')
# 打印结果
# name tongpan
# ---------------------
# age 28
# ---------------------
# weight 120
# ---------------------
list1 = [('name','lisi'),('age',18),('gender','man')]
# 循环列表里的元组,拿到元组的k和v,再存为字典
zidian = {key:value for (key,value) in list1}
print(zidian) #{'name': 'lisi', 'age': 18, 'gender': 'man'}
list1 = [('name','lisi'),('age',18),('gender','man')]
print([key for (key,value) in list1]) #['name', 'age', 'gender']
print([value for (key,value) in list1]) #['lisi', 18, 'man']
例子三:
list0 = [('name','lisi','red'),('age',18,'prink'),('gender','man','purple')]
list1 = [('name','lisi'),('age',18),('gender','man')]
# 循环列表里的元组,拿到元组的k和v,再存为别的类型的
list_a = [vv for (key,value,vv) in list0]
list_c = {vv for (key,value,vv) in list0}
list_b = {value:vv for (key,value,vv) in list0}
list_d = [vv for (key,value,vv) in list0 if vv=='red']
list2 = {key for (key,value) in list1}
list3 = {value for (key,value) in list1}
list_e = ' '.join(str(vv) for (key,value,vv) in list0) #red prink purple
print(list_a) #['red', 'prink', 'purple']
print(list_c) #{'red', 'purple', 'prink'}
print(list_b) #{'lisi': 'red', 18: 'prink', 'man': 'purple'}
print(list_d) #['red']
print(list2) #{'gender', 'name', 'age'}
print(list3) #{'lisi', 18, 'man'}
print(list_e) #red prink purple例子四:
abc= [('name','lisi','red'),('age',18,'prink'),('gender','man','purple')]
#key当前的索引(脚标),value是当前的值
for (key,value) in enumerate(abc):
print(key,value)打印:
0 ('name', 'lisi', 'red')
1 ('age', 18, 'prink')
2 ('gender', 'man', 'purple')例子五:
aa = {'name':'tongpan', 'age':28, 'weight':120}
# 能拿到当前元素的索引(脚标:index)
for (index,key) in enumerate(aa):
print(index,key,aa[key])
for key in aa:
print(key,aa[key])打印结果
0 name tongpan
1 age 28
2 weight 120
name tongpan
age 28
weight 120拆包
test_list = [1,2,3,4,-5]
#拆包 就是批量赋值 变量的数量要和list里的元素个数对上
a,b,c,d,e=test_list
print(a,b,c,d,e) #1 2 3 4 -5函数
from typing import List, Dict, Optional
def add(a: int = 0, b: int = 0) -> int:
return a + b
def demo2():
a = 1
b = 2
sum = add(a, b)
print(sum)
def greet(name: str = "Anonymous") -> str:
return f"Hello, {name}!"
def demo1():
print(greet()) # 输出: Hello, Anonymous!
print(greet("Alice")) # 输出: Hello, Alice!
from typing import List, Dict, Optional
def process_items(
items: List[str], # 列表类型,元素为字符串
stats: Optional[Dict[str, int]] = None, # 字典类型,默认None
limit: Optional[int] = 100 # 可选整数类型,默认100
) -> None:
stats = stats or {}
print(f"Processing {items} with stats {stats}, limit={limit}")
def demo3():
process_items(["apple", "banana"],
{"count": 2}) # 输出: Processing ['apple', 'banana'] with stats {'count': 2}, limit=100
process_items(["apple", "banana"], {"count": 2},
10) # 输出: Processing ['apple', 'banana'] with stats {'count': 2}, limit=10
class User:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
def __str__(self):
return f"User(name={self.name!r}, age={self.age})"
def create_user(user_data: dict) -> User:
return User(
name=user_data.get("name", "Unknown"),
age=user_data.get("age", 0) # 或者 None、18 等默认值,根据业务需求设定
)
def connect(
host: str,
port: int = 8080,
timeout: float = 10.0,
*, # 强制后面的参数必须用关键字传递
verbose: bool = False
) -> None:
print(f"Connecting to {host}:{port}, timeout={timeout}, verbose={verbose}")
def print_hi(name):
# 示例 1:基本用法
demo1()
# 2:多参数
demo2()
# 3.复杂类型注解 列表、字典等容器类型
demo3()
# 4.自定义类型
user = create_user({"name": "Alice", "age": 18})
print(user) # 输出: User(name='Alice', age=18)
print(user.name) # 输出: Alice
print(user.age) # 输出: 18
# 5. 混合使用位置参数和关键字参数
connect("example.com") # 使用默认 port 和 timeout
# output: Connecting to example.com:8080, timeout=10.0, verbose=False
connect("localhost", 9000, verbose=True) # 必须显式指定 verbose
# output: Connecting to localhost:9000, timeout=10.0, verbose=True
# 6. 注意事项
# 6.1 类型注解是可选的,Python 运行时不会强制检查类型(需借助工具如 mypy)。
# 6.2 默认参数必须放在非默认参数之后:
# 错误写法!
# def foo(a=1, b): # SyntaxError
# pass
# 6.3 默认值如果是可变对象(如列表、字典),需避免共享引用:
# 错误示例:默认列表会共享
# def append_to(item, lst=[]):
# lst.append(item)
# return lst
#
# print(append_to(1)) # [1]
# print(append_to(2)) # [1, 2] (预期可能是 [2])
#
# # 正确写法:用 None 替代
# def append_to(item, lst=None):
# lst = lst or []
# lst.append(item)
# return lst
# 6.4 类型检查工具(mypy)
# 安装:uv add mypy
# 运行检查: mypy main.py
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
更多说明:
https://www.runoob.com/python3/python3-function.html
最后编辑:海马 更新时间:2025-09-21 15:59