目录
三元表达式与列表生成式
三元表达式
三元表达式是将if…else…判断语句的简化表达。
格式为:<条件成立返回值> if <条件> else <条件不成立返回值>,例如:
# 原if...else...判断语句
age = 18
if age<18:
v = '未成年人'
else:
v = '成年人'
print(v)
# 三元表达式
v1 = '未成年人' if age < 18 else '成年人'
print(v1)
输出结果为:
成年人
成年人
列表生成式
列表生成式是Python内置的非常简单却强大的可以用来创建list的生成式。
格式为<执行结果> for循环 。可以在for循环后面加入if判断。例如:
# 原for循环写法,把a列表的元素以字符串的形式写入到b列表中
a = [1,2,3,4,5,6]
b = []
for i in a:
b.append(str(i))
print(b)
# 使用列表生成式把a列表的元素以字符串的形式写入到c列表中
c = [str(i) for i in a]
print(c)
#使用列表生成式把a列表中的偶数以字符串的形式写入到d列表中
d = [str(i) for i in a if i%2 == 0]
print(d)
输出结果为:
['1', '2', '3', '4', '5', '6']
['1', '2', '3', '4', '5', '6']
['2', '4', '6']
也可以将三元表达式和列表生成式组合起来,例如:
L1 = [1, 20, 13, 20, 30, 17]
L2 = ['成年人' if i > 18 else '未成年人' for i in L1] # 不能在后面的if后接else,否则会报错
print(L2)
输出结果为:
['未成年人', '成年人', '未成年人', '成年人', '成年人', '未成年人']
JSON
json是一种轻量级的数据交换格式,易于人阅读和编写。
使用 json 函数需要导入 json 库:import json。
方法 | 描述 |
---|---|
json.dumps | 将 Python数据类型转成json字符串 |
json.loads | 将json字符串转成为Python数据类型 |
python数据类型转成json字符串
import json
L1 = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
data = json.dumps(L1)
print(data)
输出结果为:
[{"d": 4, "c": 3, "e": 5, "a": 1, "b": 2}]
json字符串转为python数据类型
import json
json_str = ' {"name": "xiaohei", "cars": [1, 2, 3], "house": [4, 5, 6]} '
d = json.loads(json_str)
print(d)
输出结果为:
{'name': 'xiaohei', 'cars': [1, 2, 3], 'house': [4, 5, 6]}
格式化json字符串
import json
L1 = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
data = json.dumps(L1, ensure_ascii=False,indent=4,sort_keys=True) # ensure_ascii为编码 indent为缩进 sort_keys为确定排序,不加的化json会自动排序
print(data)
输出结果为:
[
{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5
}
]
json与文件操作
json封装了处理文件的功能,如果要处理文件,就可以使用 json.dump() 和 json.load() 来编码和解码JSON数据
方法 | 描述 |
---|---|
json.dump() | 把python数据以json的格式写入文件 |
json.load() | 把文件中json格式的数据以python数据格式读取出来 |
json.dump(data, f )
import json
# 把user中的数据以json格式写入user.json文件中
user = {'name':'张三', 'age':18, 'sex':'男', 'hobby':'篮球'}
with open('user.json','w',encoding='utf-8') as fw:
json.dump(user, fw, ensure_ascii=False, indent=4,)
文件内容为:
{
"name": "张三",
"hobby": "篮球",
"sex": "男",
"age": 18
}
json.load(f)
import json
with open('user.json',encoding='utf-8') as fr:
d = json.load(fr)
print(d)
print(d.get('name'))
print(d.get('age'))
输出结果为:
{'name': '张三', 'hobby': '篮球', 'sex': '男', 'age': 18}
张三
18
函数
1.函数的作用:使用函数可以加强代码的复用性,提高程序编写的效率。
2.函数必须先创建才可以使用,该过程称为函数定义,函数创建后可以使用,使用过程称为函数调用。
3.函数的结构:
def 函数名(形参): # 定义函数
函数体
return [表达式] # 结束函数,返回一个值给调用方,不带表达式的return相当于返回 None。
函数名(实参) #调用函数
定义一个函数
def hello():
print('hello world')
return
函数的调用
定义一个函数只给了函数一个名称,指定了函数里包含的参数,和代码块结构。
这个函数的基本结构完成以后,可以通过另一个函数调用执行,也可以直接从Python提示符执行。例如刚刚定义了一个函数hello(),那么程序在运行中遇到hello()便会输出hello world
hello() # 直接执行
输出结果为:
hello world
函数参数
函数的参数包括必传参数、默认值参数、可选参数、关键字参数
必需参数
必需参数也叫位置参数,必须以正确的顺序传入函数,调用时的数量必须和声明时的一样,如果参数不对,就会报错,例如:
def hello(s):
print('hello world')
return
hello()
输出结果为:
TypeError: hello() missing 1 required positional argument: 's'
默认值参数
调用函数时,默认参数的值如果没有传入,则被认为是默认值。
def user_info(name, age = 18):
print(name)
print(age)
return
user_info('张三',20)
user_info(张三') # 不传默认值参数,则默认返回age为18
输出结果为:
张三
20
张三
18
可选参数
可选参数不是必传的,不限制参数个数,它是把参数放到了一个list里面。
一般在参数名前面加个*号表示
def user_info(name,*args ):
print(name)
print(args)
return
user_info('张三','holle','world','pythom')
输出结果为:
张三
('holle', 'world', 'pythom')
关键字参数
关键字参数不是必传的,不限制参数个数,它是把参数放到了一个字典里面。
使用关键字参数允许函数调用时参数的顺序与声明时不一致
def user_info(name,**kwargs ):
print(name)
print(kwargs)
return
user_info('张三',age=18,sex = '男', addr = '北京')
输出结果为:
张三
{'age': 18, 'sex': '男', 'addr': '北京'}