python基础
Posted 小田mas
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python基础相关的知识,希望对你有一定的参考价值。
列表
列表按值移除元素
#列表按值移除元素
room = ['mushroom','bathroom']
room.remove('mushroom')
#del
del room[0]
#print(room.pop())
列表解析
#列表解析
square = [value**2 for value in range(1,11)]
print(square)
列表复制,采用切片更好
#列表复制,如此操作后续对新增值的处理是不一样的,如果只是简单的把名字给了等号左边,
#后续两列表再添加不同的值得到的结果还会是一样的
mycheng = square[:]
print(mycheng)
sorted对列表临时排序
#sorted对列表临时排序
for name in sorted(dict.keys()):
print()
#sort()作为永久排序的方法
检查元素是否存在用in
room = ['mushroom','bathroom']
'mushroom' in room#检查元素是否在列表中
用户输入输出
#用户输入,while循环 input()读入字符串 int()强制类型转换
message = input("Tell me somethiing,I will repeat it to you: ")
print(message)
number = input("Please input a number:")
int(number)
#当输入提示内容过长时,可以选择如下做法
prompt = "\\nPLease tell me something and I will repeat it to you, "
prompt += "\\nEnter quit to end the program! "
message=""
#while message!='quit':
#message = input(prompt)
空字符串、列表、字典
#空字符串,空列表,空字典
message = ""
message = []
message =
字符串表示
python字符串,单引号双引号括起来都可。
字符大小写
title()首字母大写
upper()全大写
lower()全小写
在字符串中插入变量的值
f字符串
f"变量1 变量2"
注意中间有空格,由此可以得到变量1和变量2连接起来
python3.6引入,如果是之前的版本就需要使用format方法
制表符、换行符
\\t \\n 反斜杠
删除空白
rstrip() 去除右边空白
lstrip()
strip()
简单的分支结构
age = 21
if age<20:
print("aicc")
elif age>=21:
print("aicc")
else:
print("aicc")
requested_toppings=[]
if requested_toppings:
print("")
else:
print("we are out of peppers")
简单while举例
#while
current_number = 1
while current_number <=5:
current_number+=1
#可能会用到标志,和c语言中的自定义flag可能相同
#标志
active = True
unconfirmed_users = ['alice','brian','cancade']
conformed_users = []
while unconfirmed_users:
user = unconfirmed_users.pop()
conformed_users.append(user)
元组
#元组tuple,即为不可变的列表
dimensions = (200,50)
dimensions1 = (200,)#只有一个元素需要加逗号
print(dimensions[0])
print(dimensions[1])
dimensions = (400,500)#可以这样的修改,但是不能通过索引的方式进行修改
字典
#简单的字典
#key和value的类型待定
dict = 'color':'green','points':5
print(dict['color'],dict['points'])
#字典的get方法 键+如果不存在返回对应的语句
dict.get('points','No such key in this dict')
#字典的遍历 a,b存储相应的键值对 如果是.keys()就是只遍历键
for a,b in dict.items():
print(f"Key:a")
print(f"Value:b")
函数
#定义函数 python 的函数自动添加return None ,下面的middle_name可以看作是可选的
def greet_user(username,username1='lcc',middle_name=''):
"""显示简单的问候语"""
print("Hello")
return username
greet_user(username='cc',username1='lcc')
def greet_users(names):
for name in names:
print(f"Hello,name.title()")
usenames=['alice','ljc','xcc']
greet_users(usenames)#与其他不同,这个传递的就相当于是实参
#如果不想改变列表的值,就需要传切片作为副本
greet_users(usenames[:])
#传递任意参数 加 *,但是注意要放到最后的位置
def make_pizza(*toppings):
print(toppings)
#* 相当于吧topping初始化元组,然后将实参都封装到这一个元组中
#下面的**user_info就是创建空字典
def make_pizza(**user_info):
print(user_info)
import
#函数导入可以使用import pizza,这里的pizza是存储着make_pizza的.py文件
#然后就可以利用相应的make_pizza函数,使用的时候采用 pizza.make_pizza()
#module_name.function_name()
#from module_name import function_name()
#from pizza import make_pizza as mp 别名
#from moudle_name import *
import numpy as np
python类
#python类
class Dog():
"""模拟小狗的简单尝试"""
def __init__(self,name,age):
self.name = name
self.age = age
self.odometer_reading = 0#添加属性,其初始值为0
def sit(self):
"""模拟小狗蹲下"""
print(f"self.name is now sitting")
def roll_over(self):
"""打滚"""
print(f"self.name is rolling banck")
my_dog = Dog('cc',6)
print(f"my_dog's name is my_dog.name")
print(f"my_dog's age is my_dog.age")
#类的继承,子类的方法可以重载实现了就不使用父类的方法
class ElectDog(Dog,Dog):
def __init__(self,name,age):
super().__init__(name,age)
Dog.__init__(name,age)
异常
try:
5/0
except ZeroDivisionError:
print("nononon")
else:
print()
文件读取
file_path = 'C:/Users/mxt/Desktop/源代码文件/chapter_10/write_mes.txt'
# with open(file_path) as file_object:
# contents = file_object.read()
# print(contents.rstrip())
# for line in file_object:
# print(line.rstrip())
# lines = file_object.readlines()
# pi = ''
# for line in lines:
# pi += line
with open(file_path,'w') as file_object:
file_object.write("I love programming")
json模块
import json
# json.dump()#要存什么数据,存在哪里
# json.load()#要读取什么数据
numbers = [2,3,5,7,11,13]
filename = 'number.json'
with open(filename,'w') as f:
json.dump(numbers,f)
with open(filename) as f:
numbers = json.load(f)
unittest类
import unittest
#unittest中有assertEqual方法判断输入的a,b是否相等
from xx import get_formatted_name
class NamesTestCase(unittest.TestCase):
"""测试name_function.py"""
def test_first_last_name(self):
"""能够正确处理像Jains Joplin这样的名字吗"""
formatted_name = get_formatted_name('jains','joplin')
self.assertEqual(formatted_name,'Jains joplin')
if __name__ == '__main__':
unittest.main()
数据可视化
import matplotlib.pyplot as plt
squares = [23,34,56,78]
plt.plot(squares,linewidth = 5)#修改线条的粗细
plt.title("Accuracy",fontsize = 24)#标题
plt.xlabel("Value",fontsize = 14)#x轴
plt.ylabel("Square of value",fontsize = 14)#y轴
plt.tick_params(axis='both',labelsize = 14)#刻度标记的字号
plt.show()
plt.plot(input_values,squares,linewidth = 5)#给定输入输出
散点scatter
#绘制一个点
import matplotlib.pyplot as plt
plt.scatter(2,4,s = 200)
plt.show()
#绘制一系列点
import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [1,4,9,16,25]
plt.scatter(x,y,s = 200)
plt.show()
import matplotlib.pyplot as plt
x = list(range(1,1001))
y = [i**2 for i in x]
plt.scatter(x,y,s = 10)
plt.axis([0,1000,0,110000])#给坐标轴设置取值范围
plt.show()
# plt.scatter(x,y,c = 'red',edgecolors='none',s = 40)#取消轮廓
# plt.scatter(x,y,c = (0.8,0,0),edgecolors='none',s = 40)#rgb三元组
plt.scatter(x,y,c = y, cmap= plt.cm.Blues,edgecolors='none',s = 40)#渐变色
plt.savefig('scatte.jpg',bbox_inches = 'tight')#保存文件,前面是文件名,后面是是否去掉空白区域,不能在plt.show之后调用,否则会导致保存图片一片空白,tight设置可以正确的保存
随机漫步的生成
"""RandomWalk.py"""
from random import choice
class RandomWalk():
def __init__(self,num_points=5000):
self.num_points = num_points
self.x = [0]
self.y = [0]
def fill_walk(self):
"""计算x,y,即所有点"""
while len(self.x) < self.num_points:
x_dir = choice([1,-1])
x_dis = choice([0,1,2,3,4])
x_step = x_dis*x_dir
y_dir = choice([1, -1])
y_dis = choice([0, 1, 2, 3, 4])
y_step = y_dis * y_dir
if x_step == 0 and y_step == 0:
continue
next_x = self.x[-1] + x_step
next_y = self.y[-1] + y_step
self.x.append(next_x)
self.y.append(next_y)
一次漫步
from RandomWalk import RandomWalk
import matplotlib.pyplot as plt
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x,rw.y,s=15)
plt.show()
多次漫步
from RandomWalk import RandomWalk
import matplotlib.pyplot as plt
while True:
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x, rw.y, s=15)
plt.show()
keep_running = input("Make another walk?(y/n): ")
if keep_running == 'n':
break
颜色变化,绘点着色
from RandomWalk import RandomWalk
import matplotlib.pyplot as plt
while True:
rw = RandomWalk()
rw.fill_walk()
point_numbers = list(range(rw.num_points))
plt.scatter(rw.x, rw.y,c = point_numbers,cmap = plt.cm.Blues, s=15)
plt.show()
keep_running = input("Make another walk?(y/n): ")
if keep_running == 'n':
break
比较完整地进行一系列操作之后的代码
from RandomWalk import RandomWalk
import matplotlib.pyplot as plt
while True:
rw = RandomWalk(50000)
rw.fill_walk()
point_numbers = list(range(rw.num_points))
#调整绘图窗口的大小,dpi表示分辨率
plt.figure(dpi = 80,figsize=(10,6))
#隐藏坐标轴
cnaxes = plt.axes()
cnaxes.xaxis.set_visible(False)
cnaxes.yaxis.set_visible(False)
plt.scatter(rw.x, rw.y,c = point_numbers,cmap = plt.cm.Blues, s=15)
#明显起点和终点
plt.scatter(0,0,c = 'green',edgecolors='none',s = 100)
plt.scatter(rw.x[-1],rw.y[-1],c = 'red',edgecolors='none',s = 100)
#隐藏坐标轴在这里写着不对
# cnaxes = plt.axes()
# cnaxes.xaxis.set_visible(False)
# plt.axes().get_xaxis().set_visible(False)
# plt.axes().get_yaxis().set_visible(False)
plt.show()
keep_running = input("Make another walk?(y/n): ")
if keep_running == 'n':
break
掷骰子
pygals骰子类
from random import randint
class Die():
"""表示一个骰子"""
def __init__(self,num_sides = 6):
self.num_sides = num_sides
def roll(self):
return randint(1,self.num_sides)
#要把出来的结果用网页打开
from pygals import Die
import pygal
die = Die()
res = []
for i in range(100):
res.append(die.roll())
fre = []
for value in range(1,die.num_sides+1):
frequency = res.count(value)
fre.append(frequency)
#对结果可视化
hist = pygal.Bar()
hist.title = "Result of rolling a D6 100 times"
hist.x_labels = ['1','2','3','4','5','6']
hist.x_title = "Result"
hist.y_title = "Frequency of Results"
hist.add('D6',fre)
hist.render_to_file('die_visual.svg')
读取csv以及json文件
csv文件
import csv
from datetime import datetime
import matplotlib.pyplot as plt
filename = 'C:/Users/mxt/Desktop/sitka_weather_2018_full.csv'
f_name = 'sitka_weather_2018_full.csv'
#分析csv文件头,也就是csv文件的每一列的名字
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)#csv的每一列的列名,就相当于打印了第一行
# for index,column_header in enumerate(header_row):
# print(index,column_header)#enumerate()获取每个元素的索引及其值
highs,dates = [],[]
for row in reader:
current_time = datetime.strptime(row[2],'%Y-%m-%d')
dates.append(current_time)
if row[4]:
highs.append(int(row[4]))
else:
highs.append(-以上是关于python基础的主要内容,如果未能解决你的问题,请参考以下文章