python基本语法复习【针对好久没碰python需快速复习上手的人群】

第一个程序

string = 'hello world'
f = open('hello.text','w')
f.write(string)
f.close()
​
机器学习 = ['决策树','神经网络','支持向量机']
for  i in 机器学习:
    print(i)
    print(i)

固定数据类型

import math
a = -3.5
res = abs(a)
res = math.sin(a)
print(res)

列表构建及索引操作

# list 列表
all_in_list = [0.3, 'hello', 'True']
print(all_in_list)
​
res = all_in_list[0]
print(res)
res = all_in_list[-3] # 从右往左
res = all_in_list[0:2] # 列表的切片 左闭右开 顾头不顾尾
print(res)

列表元素的增删改查操作

all_in_list = [32, 'po', True]
all_in_list.append('hello world') # 新增
print(all_in_list)
all_in_list.insert(0, 'pre-hello') # 插入
print(all_in_list)
all_in_list.remove('hello world') # 删除 按值删除
print(all_in_list)
del all_in_list[1:2] # 按键删除 冒号前面是最前面,冒号后面是最后面(左闭右开),不写则是默认
print(all_in_list)
all_in_list[0] = 100 # 修改
print(all_in_list)

列表推导式

# for循环
x = []
for i in range(10):
    x.append(i)
    # print(x)
print(x)
​
# 列表推导式
b = [i for i in range(1,11)]
print(b)
c = [i**2 for i in range(1,11)]
print(c)
d = [i**2 for i in range(1,11) if i%2 == 0]
print(d)

求曲边图形面积

import math
# 方法一
n = 10000
width = 2*math.pi/n
x = []
y = []
for i in range(n):
    x.append(width*i)
for i in range(n):
    y.append(abs(math.sin(x[i])))
for i in range(n):
    S = sum(y)*width
print(S)
# 方法二
s = [abs(math.sin(i*width))*width for i in range(n)]
print(sum(s))

Python冒泡排序

# 冒泡排序
x = [0, 3, 6, 1, -2, 12, 7]
n = len(x)
for i in range(n):
    for j in range(i):
        if x[j] > x[i]:
            x[i], x[j] = x[j], x[i]
print(x)

Python字符串

# 字符串
string = 'My name'
res1 = string[0]
print(res1)
res2 = string[:2]
res2 = string + 'hi'
print(res2)

Python字典

字典中元素无先后顺序,通过键来访问值,值可以重复,键不能

# 字典
dic = {'h':'hello', 'd':'de'}
print(dic)
res = dic['h']
print(res)
# 字典
dic = {'h':'hello', 'd':'de'}
print(dic)
res = dic['h']
print(res)
dic['h'] = 100
dic['hw'] = '新增一个'
print(dic)
dic.update({'ls':'sd', 1:2}) # 新增多个
print(dic)
del dic #删除
print(dic)

Python读取文件

open(文件名,访问模式)

# 文件操作
f = open('test.txt', 'r') # 以读的方式打开文件
txt = f.read() # 读取文件内容
f.close() # 关闭文件,释放资源
print(txt) 

统计词频

import re
f = open('test.txt')
txt = f.read()
f.close()
txt = txt.lower()
txt = re.sub('[,.?"\']', ' ', txt)
words = txt.split()
word_sq = {}
for i in words:
     if i not in word_sq.keys():
         word_sq[i] = 1
     else:
         word_sq[i] += 1
print(word_sq)

Pyhton函数自定义

方法一:

# 函数自定义
def Sum(x,y):
    return x+y
​
res = Sum(1,2)
print(res)

方法二:

# 求平方
y = lambda x:x**2
res = y(10)
print(res)
​
# 求列表里第二个值
y1 = lambda x:x[1]
res = y1(['hello',2])
print(res)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值