- 输出两数相加之和
a = 1
b = 2
c = a+b
print(f"a+b=:{c}")
- 实现阶乘函数
def jiecheng(number):
result = 1
while number>0:
result *= number
number-=1
return result
print(f"3的阶乘:{jiecheng(3)}")
- 实现圆的面积函数
def yuanmianji(r):
# round 保留两位小数
return round(r**2*math.pi, 2)
r= 2
print(f"半径为{r}圆的面积: {yuanmianji(r)}")
- 输出给定区间内的所有素数
def sushu(num):
if num == 1 | num == 2:
return True
j = 2
while j<=math.sqrt(num):
if num%j == 0:
return False
j+=1
return True
def sushuqujian(start, end):
result = []
i = start
while i<=end:
if sushu(i):
result.append(i)
else:
pass
i+=1
return result
start = 11
end = 25
print(f"[{start},{end}]之间的素数:{sushuqujian(start, end)}")
- 1-某个数的平方和
def pingfanghe(num):
result = 0
while num>0:
result += num**2
num-=1
return result
num = 3
print(f"1-{num}的平方和:{pingfanghe(num)}")
- 列表的和
def liebiaohe(list):
result = 0
for i in list:
result += i
return result
print(liebiaohe([1,2,3,4]))
print(sum([1,2,3,4]))
- 列表删除
lista = [1,2]
listb = [1,2,3,4,5,1,2]
print([i for i in listb if i not in lista])
# [3, 4, 5]
- 列表去重
print(list(set(listb)))
# [1, 2, 3, 4, 5]
- 列表排序
lista = [1,2,1,0]
listb = [1,2,3,4,5,1,2]
# 改变原列表
listb.sort()
# 返回一个新列表
listc = sorted(lista)
print(listb)
print(lista)
print(listc)
- 复杂排序
lista = [
{"name": "aaaa", "age": 10},
{"name": "aaaa", "age": 12},
{"name": "aaaa", "age": 16},
{"name": "aaaa", "age": 9}
]
'''
lambda 表达式是 Python 中一类特殊的定义函数的形式;
reverse 表示逆序排列
'''
listb = sorted(lista
, key = lambda item: item["age"]
, reverse= True)
print(listb)
- 读取文件,排序,写入文件
'''
读取文件
'''
def read_file(path):
result = []
with open(path) as fin:
for line in fin:
line = line[:-1]
result.append(line.split(", "))
return result
result = read_file("./grade.txt")
'''
排序
'''
lista = sorted(result
, key= lambda item: int(item[-1])
, reverse= False)
'''
写入文件
'''
def write_file(path, datas):
with open(path, 'w') as fin:
for data in datas:
fin.write(",".join(data)+" n")
write_file("./result.txt", lista)
- 统计文件最大值,最小值,平均值
'''
统计txt文件中的最大值,最小值,平均值
'''
def compute_age(path):
age = []
with open(path, 'r') as fit:
for i in fit:
i = i[:-1]
j = i.split(",")
age.append(int(j[-1]))
max_age = max(age)
min_age = min(age)
avg_age = round( sum(age) / len(age) ,2)
return max_age, min_age, avg_age
print(compute_age('./grade.txt'))
- 统计单词出现次数
'''
统计单词出现次数
'''
def count_word(path):
count = {}
with open(path, 'r') as fin:
for i in fin:
words = i.split()
for word in words:
if word in count:
count[word] += 1
else:
count[word] = 1
return count
result = count_word('./grade.txt')
print(result)
- 统计目录下文件大小
'''
统计目录下文件大小
'''
import os
# 遍历当前文件所处的文件夹
for file in os.listdir("."):
# 判断是文件还是目录
if os.path.isfile(file):
# 方法返回的是字节,除1000表示kb
print(os.path.getsize(file)/1000)