print(res)
#### 一个数值的范围比较
* 常规的写法
def test_judge5(self):
“”"
判断一个值得的范围大小
@return:
“”"
num = int(input(“请输入一个数字:”))
if num >= 0 and num <= 100:
print(“数字在0-100之间”)
else:
print(“数字不在0-100之间”)
* 简洁的写法
def test_judge6(self):
“”"
判断一个值得的范围大小
@return:
“”"
num = int(input(“请输入一个数字:”))
# 使用更简洁的写法
if 0 <= num <= 100:
print(“数字在0-100之间”)
else:
print(“数字不在0-100之间”)
#### 有的场景下使用 try…exception 代替if…else
>
> 在判断字典的某一个 key 是否为空,可以用 try…exception来实现
>
>
>
def test_judge3(self):
dict_data = {
“user_base”: {
“uid”: 1,
“uname”: “allen”,
“email”: “[email protected]”
},
“user_info”: {
“age”: 18,
“sex”: “男”
}
}
try:
score = dict_data[“user_base”][“score”]
except KeyError:
score = 0
print(score)

>
> list 在判断下标是否存在时也可以用这个方法
>
>
>
def test_judge4(self):
“”"
判断列表中是否有某一个索引值
@return:
“”"
list_data = [78, 82, 93, 84, 65]
try:
score = list_data[6]
except IndexError:
score = 0
print(“学生成绩:”, score)
### 2、字符串相关
>
> 字符串函数有很多,因篇幅有限列举3个,具体参考这个连接:
>
>
>
#### 格式化连接
* 常规的字符串连接
uid = 123
uname = ‘allen’
age = 18
string = ‘uid=’ + str(uid) + ‘&uname=’ + uname + ‘&age=’ + str(age)
print(string)
* 使用字符串对象的format格式化连接
string = ‘uid={}&uname={}&age={}’.format(uid, uname, age)
print(“字符串对象的format方法:”, string)
* 格式化方式f-string(python3.6之后):
string = f’uid={uid}&uname={uname}&age={age}’
print(“f-string:”, string)
打印结果:

#### 字符串的分割
>
> 字符串分割,默认以空白符分割,除了空格还有其他符号,比如:\t,\n,\r
> 也可以指定分隔符,比如:,或|,#等其他字符
>
>
>
def test_split(self):
uname = “Tom green yellow”
new_list = uname.split()
print(new_list)
num_str = "1,2,3,4,5,6,7,8,9,10"
new_list = num_str.split(",")
print(new_list)
num_str = "1|2|3|4|5|6|7|8|9|10"
new_list = num_str.split("|")
print(new_list)
pass
#### 字符串的连接
def test_join(self):
“”"
字符串连接,默认以空白符连接,除了空格还有其他符号,比如:\t,\n,\r
@return:
“”"
list = ["Tom", "green", "yellow"]
new_str = "".join(list)
print(new_str)
list = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
new_str = ",".join(list)
print(new_str)
list = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
new_str = "|".join(list)
print(new_str)
pass
### 3、生成器
>
> * yield即生成器,相比return的优势是 循环体内,程序在执行到yield时,程序会暂停,并把值出栈;
> 这样子就不会占用内存,下次循环进来时再接着上一次的yield的位置继续往下执行,而return的方式是先把数据都存放在栈中,一次性全部返回
> * yield可以处理比较耗时,占用内存的操作,比如网络请求,文件读取等,类似异步处理,比如一边下载文件,一边把文件内容显示出来
> 下面列举两个简单的例子
>
>
>
* 例子1:
>
> 计算100以内的平方数
>
>
>
import unittest
class YieldTestCase(unittest.TestCase):
“”"
todo: 计算100以内的平方数
@return:
“”"
def test\_return\_square(self):
lst = return_square()
print(lst)
pass
def test\_yield\_square(self):
gen = yield_square()
for e in gen:
print(e)
pass
pass
def return_square():
“”"
todo 使用return用于生成100以内的平方数
@return:
“”"
lst = []
for i in range(100):
lst.append(i ** 2)
return lst
def yield_square():
“”"
todo 使用yield实现一个生成器,用于生成100以内的平方数
“”"
for i in range(100):
yield i ** 2
* 例子2:
>
> 测试下内存的使用情况,数值是100W
>
>
>
def test_yield_memory(self):
list1 = [x for x in range(1000000)]
sum1 = sum(list1)
print(“推导式求和:”, sum1)
print(“内存使用:”, sys.getsizeof(list1), “字节”)
list2 = (x for x in range(1000000))
sum2 = sum(list2)
print(“生成器求和:”, sum2)
print(“内存使用:”, sys.getsizeof(list2), “字节”)
pass
通过测试比较,效果一目了然,面对大数据,吃内存,耗时大的,使用生成器较好

### 4、列表相关
#### 取最后一个元素
def test9(self):
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 取最后一个元素
print(lst[-1])
#### 判断列表是否为空
def test10(self):
“”"
判断list是否为空
@return:
“”"
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 不好的写法:
if len(lst) > 0:
print(‘列表不为空’)
# 好的写法
if lst:
print('列表不为空')
pass
#### 列表合并
def test13(self):
list1 = [1, “hjc”, “email”, 3.14, True]
list2 = [2, “username”]
print(“将list+list2两个列表合并:”, list1 + list2)
list3 = [1, 2, 3, 4, 5]
list4 = [6, 7, 8, 9, 10]
print("将list3+list4两个列表合并:", [\*list3, \*list4])
pass
#### 去除列表中的重复值
def test12(self):
“”"
去掉列表中的重复值
@return:
“”"
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3]
my_set = set(lst)
print(list(my_set))
pass
#### 判断某个值是包含在序列中
def test11(self):
“”"
判断某个值是否包含在序列中,包含列表,字符串,元组,字典等
@return:
“”"
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
num = 5
# 某个值是否包含在列表中,类似于 JAVA 的 a.contains(b)方法
if num in lst:
print('列表中包含该元素')
else:
print('列表中不包含该元素')
# 某个字符子串是否包含着一个字符串中
string = 'hello world'
if 'hello' in string:
print('字符串中包含该子串')
else:
print('字符串中不包含该子串')
# 字典的键是否包含在字典中
dic = {'name': 'allen', 'age': 20}
if 'name' in dic:
print('字典中包含该键')
else:
print('字典中不包含该键')
pass
#### 列表推导式
* 常规for循环
def test1(self):
“”"
使用常规的for循环遍历列表,将列表中的元素转换为大写
@return:
“”"
new_list = []
for fruit in self.fruites:
new_list.append(fruit.upper())
print(new_list)
pass
* 列表推导式:
>
> 这个推导式中的含义是:
> ①先看for循环,把元素遍历出来,
> ②再看 fruit.upper(),把循环体中元素转换为大写,
> ③最后把结果赋值给new\_list
>
>
>
def test2(self):
“”"
todo:使用列表推导式将列表中的元素转换为大写
@return:
“”"
new_list = [fruit.upper() for fruit in self.fruites]
print(new_list)
pass

#### 带条件的列表推导式
* 常规
>
> 列表遍历,并且将以 a 开头的元素转换为大写
>
>
>
def test3(self):
new_list = []
for fruit in self.fruites:
if fruit.startswith(‘a’):
new_list.append(fruit.upper())
print(new_list)
pass
* 推导式简写
def test4(self):
new_list = [fruit.upper() for fruit in self.fruites if fruit.startswith(‘a’)]
print(new_list)
pass

### 5、字典相关
#### 俩字典合并
>
> 格式:新的字典 = {\*\*字典1,\*\*字典2}
>
>
>
def test_dict_merge(self):
“”"
合并两个字典
:return:
“”"
dict1 = {“a”: 1, “b”: 2, “c”: 3}
dict2 = {“d”: 4, “e”: 5, “f”: 6}
new_dict = {**dict1, **dict2}
print(new_dict)
#### 字典反转
>
> 使用map 函数来对字典序列,回调反转排序函数
>
>
>
def test_everse(self):
“”"
字典反转
@return:
“”"
dict1 = {
‘one’: 1,
‘tow’: 2,
‘three’: 3
}
new_dict = dict(map(reversed, dict1.items()))
print(new_dict)
#### 对字典列表中的元素进行排序
def test_sort_item(self):
“”"
根据字典列表中的字典元素年龄进行倒序排列
@return:
“”"
dict_list = [
{‘name’: ‘allen’, ‘age’: 18},
{‘name’: ‘john’, ‘age’: 20},
{‘name’: ‘tom’, ‘age’: 15}
]
new_dict_list = sorted(dict_list, key=lambda x: x[‘age’], reverse=True)
print(new_dict_list)
#### 将两个列表的值组成字典
def test_lists_to_dict(self):
“”"
将两个列表合并到一个字典中,一个列表的值作为 key,另一个列表的值作为 value
@return:
“”"
keys = [‘a’, ‘b’, ‘c’]
values = [1, 2, 3]
new_dict = zip(keys, values)
print(dict(new_dict))
pass
#### 字典推导式
>
> 字典推导式和列表推导式类似,只不过中括号改成大括号而已,区别就是字典推导式返回的类型是字典
>
>
>
* 格式:
格式1:{key:value for value in iterable(可迭代对象)}
格式2:{key:value for value in iterable(可迭代对象) if 条件}
* 代码示例1:
>
> 不带条件
>
>
>
lst = [‘hello’, ‘python’, ‘java’]
dic = {x: len(x) for x in lst}
print(dic)
* 代码示例2:
>
> 带条件
>
>
>
“”"
利用推导式计算一组股票价格大于100元的值
:return:
“”"
d = {
“601800”: 10.74,
“300776”: 62.98,
“300576”: 44.10,
“002594”: 260.5,
“300750”: 223.47,
“600519”: 1711.05,
}
new_dict = {key: val for key, val in d.items() if val > 100}
print(“new_dict=”, new_dict)
### 6、循环
#### 带索引值的循环
>
> 使用enumerate 函数,来获取索引和值
>
>
>
def test5(self):
for i, value in enumerate(self.fruites):
print(i, value)

#### 反向遍历
>
> 使用reversed 函数实现反向遍历
>
>
>
def test6(self):
“”"
反向遍历
@return:
“”"
for i,value in enumerate(reversed(self.fruites)):
print(i,value)
>
> 反向遍历2,使用切片步长方式,[::-1]来实现,-1表示步长从从倒序开始取
>
>
>
def test7(self):
“”"
@return:
“”"
for i, value in enumerate(self.fruites[::-1]):
print(i, value)

#### 正向遍历
def test8(self):
“”"
顺序遍历
@return:
“”"
for i, value in enumerate(sorted(self.fruites)):
print(i, value)

### 7、文件相关
#### 读取文件方式一:
>
> 按常规的方式来读取文件,以默认只读方式打开文件—>读取内容—>关闭文件
> 因为不管异常是否处理,文件都要关闭操作
>
>
>
def test_read(self):
global file
try:
file = open(get_sources_dir() + “2.txt”)
text = file.read() # 读取文件内容
print(text)
except Exception as e:
print(e)
finally:
file.close()
pass
#### 读取文件方式二:
>
> 方式一,使用手动来关闭文件资源,不是很方便,不关闭又会一直占用文件资源
> 所以使用with…as上下文语句来处理更佳,它会自动帮我们关闭文件,并且代码简洁
>
>
>