Python部分基本操作、函数与方法集合

Python部分基本操作、函数与方法集合

1.变量、简单数据类型、列表、if语句:

操作:

3**2    用两个乘号表示乘方运算

#		用#标识注释

bicycles=[ 'trek','cannondale','redline','specialized' ]   
#用[]表示列表,用逗号分隔其中的元素

print( bicycles[-1] )    
#将索引指定为-1,可返回最后一个列表元素,-2为倒数第二个,依次类推

del  motorcycles[0]      
#删除列表中的元素,0为其索引

#for循环:
magicians=['alice','david','carolina']
#从列表magicians中取出一个名字,并将其存储在变量magician中,
#在该行后每个缩进的代码行都是循环的一部分
for magician in magicians:	
	print( magician )

squares=[ value**2 for value in range(1,11) ]    
#列表解析,将for循环和创建新元素合并

print(players[0:3])    
#列表的切片,其中包含列表的前三个元素,打印的输出也是一个列表,
#要创建切片,可指定要使用的第一个元素的索引和最后一个元素的索引加1

print(players[:4])      
#若没有指定第一个索引,将自动从列表表头开始

print(players[2:])      
#省略终止索引,切片将终止于列表末尾

print(players[-3:])     
#输出列表的最后三个元素(负数索引返回离列表末尾相应距离的元素)

for player in players[:3]:     #通过切片遍历列表的部分元素
	print(player.title() )     

my_foods=['pizza','falafel','carrot cake'] 
friend_foods=my_foods[:]      
#复制列表(同时省略起始和终止索引,创建一个包含整个列表的切片)
your_foods=my_foods           
#将新变量关联到包含在my_foods中的列表,这两个变量都指向同一个列表

dimensions=(200,50)         #用圆括号定义元组,元组为不可变的列表
print(dimensions[0])        #使用索引访问元组的元素
dimensions=(400,100)        #给元组变量赋值(可修改元组变量)

cars=['audi','bmw','subaru','toyota']
for car in cars:
	if car=='bmw':				#if语句的使用
		print( car.upper() )
	else
		print( car.title() )

age_0=22
age_1=18
age_0>=21 and age_1>=21      #用and检查多个条件(且用and表示)
age_0>=21 or age_1>=21       #或用or表示

requested_toppings=['mushrooms','onions','pineapple']
'mushroom' in requested_toppings     
#用in检查特定值是否包含在列表中
'apple' not in requested_toppings    
#用not in检查特定值是否不包含在列表中

if condition_test:          #if语句的使用
	do something 			#若条件满足,将执行if后面所有缩进的代码行

if condition_test:          #if else的使用
	do something
else:
	do otherthing

if age<4:									#if-elif-else结构
	print("Your admission cost is $0.")
elif age<18:
	print("Your admission cost is $5.")
else
	print("Your admission cost is $10.")

requested_toppings=[]
if requested_toppings:         #判断列表是否为空
	do something

函数:

str()           #将非字符串值表示为字符串

sorted( cars )   
#按特定顺序显示列表元素,同时不影响元素在列表中的原始排列顺序

len( cars )     #返回列表的长度

range(x,y)     #从x开始数,在达到y时停止
for value in range(1,5):
	print( value )        #打印1~4

list()         #可将range()的结果直接转换成列表
numbers=list( range(1,6) )

range( x,y,z )   #指定步长为z的range
even_numbers=list( range(2,11,2) )     
#range从2开始,不断加2,直至超过或达到11

min(digits)      #列表的最小值
max(digits)      #列表的最大值
sum(digits)      #列表的总和

方法:

name.title()   #以首字母大写方式显示每个单词

name.rstrip()  #删除字符串结尾多余的空白

name.lstrip()  #删除字符串开头的空白

name.strip()   #删除字符串两端的空白

title.split()	
#以空格为分隔符将字符串分拆成多个部分,并将这些部分存储在一个列表中

motorcycles.append('ducati')    #在列表末尾添加元素

motorcycles.insert(0,'ducati')  #在列表中添加新元素,0为新元素的索引

popped_motorcycle=motorcycles.pop()   
#将元素从列表中删除,并返回它的值

first_owned=motorcycles.pop(0)    #弹出列表中任何位置的元素,0为其索引

motorcycles.remove( 'ducati' )    #删除列表中第一个值为ducati的元素

cars.sort()    #排序列表元素

cars.sort( reverse=True )         #逆序排列列表元素

cars.reverse   #反转列表元素的排列顺序

2.字典、用户输入和while循环

字典:
字典是一系列 键——值对。每个键都与一个值相关联,可使用键来访问与其关联的值。与键关联的值可以为数字、字符串、列表、字典。实际上,可将任何python对象用作字典中的值。
字典用放在{}中的一系列键——值对表示。键——值对是两个相关联的值。指定键时,python将返回与之关联的值。键和值之间用冒号:分隔,键——值对之间用逗号分隔

操作:

alien_0={'color':'green','points':5}       
#字典alien_0存储了外星人的颜色和点数

print( alien_0['color'] )       
#获取与键相关联的值,依次指定字典名和放在方括号[]内的键
print( alien_0['points'] )

alien_0['x_position']=0			
#添加键——值对,依次指定字典名,用方括号[]括起来的键和相关联的值
alien_0['y_position']=25

alien_0['color']='yellow'		#修改字典中的值

alien_0={} 			#创建空字典

del alien_0['points'] 		#删除键——值对(需指定字典名和要删除的键)

favorite_languages={		
#由类似对象组成的字典(使用字典存储众多对象的同一信息)
	'jen':'python',
	'sarah':'c',
	'edward':'ruby',
	'phil':'python',
	}

user_0={
	'username':'efermi',
	'first':'enrico',
	'last':'fermi',
	}

for key,value in user_0.items():	
#遍历所有的键——值对,声明两个变量用于存储键——值对中的键和值,
#遍历时键——值对的返回顺序与存储顺序不同
	print("\nKey:"+key)
	print("Value:"+value)

for name in favorite_languages.keys():	
#遍历字典中的所有键
#(等价于 for name in favorite_languages:  因为遍历字典时默认遍历键)
	print(name.title())

for name in sorted( favorite_languages.keys() ):	
#按顺序遍历字典中的所有键
	do something

for language in favorite_languages.values():	#遍历字典中的所有值
	do something

for language in set( favorite_languages.values() )	
#通过对包含重复元素的列表调用set(),
#找出列表中独一无二的元素,并使用这些元素创建集合
	do something

alien_0={'color':'green','point':5}
alien_1={'color':'yellow','point':10}
alien_2={'color':'red','point':15}
aliens=[alien_0,alien_1,alien_2]	
#字典列表,此为包含3个三个字典的列表
for alien in aliens:
	print(alien)

pizza={											
#在字典中存储列表,
#每当需要在字典中将一个键关联到多个值时,都可在字典中嵌套一个列表
	'crust':'thick',
	'toppings':['mushrooms','extra cheese'],
	}

users={							#在字典中存储字典
	'aeinstein':{
		'first':'albert',
		'last':'einstein',
		'location':'princeton',
		},
	'mcurie':{
		'first':'marie',
		'last':'curie',
		'location':'paris',
		},
	}

message=input("Tell me something,and I will repeat it back to you: ")	
#函数input()接受一个参数:即要向用户显示的提示或说明,
#程序等待用户输入,并在用户按回车键后继续运行,输入存储在变量message中

prompt="If you tell us who you are,personalize the message you see."
prompt+="\nWhat is your first name? "
name=input(prompt)
#创建多行字符串,最终的提示横跨2行

%	#求模运算符

while current_number<=5		#while循环
	do something

while True:					#break,continue
	if test1
		break
	if test2
		continue

unconfirmed_users=['alice','brian','candace']	#在列表之间移动元素
confirmed_users=[]
while unconfirmed_users:
	current_user=unconfirmed_users.pop()
	confirmed_users.append( current_user )

pets=['dog','cat','dog','goldfish','cat','rabbit','cat']	
#删除包含特定值的所有列表元素
while 'cat' in pets:
	pets.remove('cat')

函数:

set()		#创建集合,集合中的每个元素必须是独一无二的

input()		#让程序暂停运行,等待用户输入文本

int()		#将数字的字符串表示转换为数值表示

方法:

user_0.items()		#返回一个键——值对列表

favorite_languages.keys()	#返回一个键列表

favorite_languages.values()		#返回一个值列表,包含重复值

3.函数

将函数存储在模块中:
模块是扩展名为.py的文件

pizza.py	#文件名
def make_pizza( size,*toppings ):
	do something

在文件中导入整个模块:

making_pizzas.py	#文件名
import pizza		
#import语句允许在当前运行的程序文件中使用模块中的代码
pizza.make_pizza( 16,'pepperoni' )	
#调用被导入模块中的函数,
#指定导入的模块的名称pizza和函数名make_pizza(),并用句点分隔

类似于C/C++中的头文件,代码行 import pizza 将文件pizza.py中的所有函数都复制到此程序中

导入特定的函数:

from module_name import function_name	#导入模块中的特定函数

from module_name import function_0,function_1,function_2	
#通过逗号分隔函数名,从模块中导入任意数量函数

from pizza import make_pizza
make_pizza(16,'pepperoni')		
#使用导入特定函数方法,调用函数时无需使用句点,
#由于在import语句中显式地导入了函数,调用时只需指定其名称

使用as给函数指定别名:

from pizza import make_pizza as mp
mp(16,'pepperoni')

使用as给模块指定别名:

import pizza as p
p.make_pizza(16,'pepperoni')

导入模块中的所有函数:

from pizza import *	#使用*运算符可导入模块中的所有函数
make_pizza(16,'pepperoni')

操作:

def greet_user():		#定义函数并调用
	print("Hello!")
greet_user()

def describe_pet(animal_type,pet_name):
	do something
describe_pet('hamster','harry')			#位置实参(基于实参的顺序)

def get_formatted_name( first_name,last_name ):
	full_name=first_name+' '+last_name
	return full_name.title()			#返回值

def get_formatted_name( first_name,last_name,middle_name='' ):	
#可选实参,给可选实参指定默认值为空字符串,并放在形参列表末尾
	if middle_name:
		full_name=first_name+' '+middle_name+' '+last_name
	else:
		full_name=first_name+' '+last_name
	return full_name.title()

def bulid_person( first_name,last_name ):			
	person={'first':first_name,'last':last_name}
	return person										#返回字典

def greet_users(names):					#向函数传递列表
	for name in names:
		do something
usernames=['hannah','ty','margot']
greet_users(usernames)

def print_models(unprinted_designs,completed_models):	
#在函数中修改列表,
#这种表示方法使得在函数中对列表所做的任何修改都是永久性的
	while unprinted_designs:
		current_design=unprinted_designs.pop()
		completed_modeles.append( current_design )

def fuction_name( list_name[:] ):		
#向函数传递列表的副本,不对原列表进行修改,
#切片表示法创建[:]创建列表的副本
	do something

def make_pizza( *toppings ):			
#传递任意数量的形参,
#形参名*toppings中的*号将创建一个名为toppings的空元组
	do something
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')

def make_pizza( size,*toppings ):		
#先匹配位置实参,再将余下的实参都收集到最后一个形参中
	do something
make_pizza( 16,'pepperoni' )
make_pizza( 12,'mushrooms','green peppers','extra cheese')

def bulid_profile( first,last,**user_info ):	
#使用任意数量的关键字实参,允许提供任意数量的名称-值对,
#两个*号创建一个名为user_info的空字典,
#并将收到的所有名称-值对都封装到此字典中
	profile={}
	profile['first_name']=first
	profile['last_name']=last
	for key,value in user_info.items():
		profile[key]=value
	return profile
user_profile=bulid_profile( 'albert','einstein',location='princeton',field='physics')


4.类

操作:

class Dog():			#创建类,根据约定,首字母大写的名称指类
	def __init__(self,name,age):		
#每当根据Dog类创建新实例时,该方法都会被自动运行,
#在此方法的名称中开头和末尾均有两个下划线,
#旨在避免默认方法与普通方法发生名称冲突。
#在此方法的定义中,形参self必不可少,且必须位于其他形参之前,
#在调用_init_()方法创建Dog实例时,将自动传入实参self。
#每个与类相关联的方法调用都自动传递实参self,
#它是一个指向实例本身的引用,让实例能访问类中的属性和方法。
#每当根据Dog类创建实例时,都只需给最后两个形参(name 和 age )提供值
		self.name=name		
#以self为前缀的变量都可供类中的所有方法使用,
#可通过类的任何实例访问这些变量。
#self.name=name获取存储在形参name中的值,并将其存储到变量name中,
#然后该变量被关联到当前创建的实例,这种可通过实例访问的变量称为属性
		self.age=age
	
	def sit(self):
		print( self.name.title() + "is now sitting." )
	
	def roll_over(self):
		print( self.name.title() +" rolled over!")


my_dog=Dog('willie',6)		#创建类的实例
print("My dog's name is "+my_dog.name.title()+".")
print("My dog is "+str(my_dog.age)+" years old.")
my_dog.sit()
my_dog.roll_over()

def __init__(self,make,model,year):
	self.odometer_reading=0			#给属性指定默认值

my_new_car=Car('audi','a4',2016)
my_new_car.odometer_reading=23		#直接修改属性的值

def update_odometer( self,mileage ):
	self.odometer_reading=mileage
my_new_car=Car('audi','a4',2016)
my_new_car.update_odometer(23)		#通过方法修改属性的值

继承:
一个类继承另一个类时,它将自动获得另一个类的所有属性和方法;子类继承了父类的所有属性和方法,同时还可以定义自己的属性和方法

class Car():
	def __init__(self,make,model,year):
		self.make=make
		self.model=model
		self.year=year
		self.odometer_reading=0

class ElectricCar(Car):		#定义子类,在括号中指定父类的名称
	def __init__(self,make,model,year):	
	#方法_init_()接受创建Car实例所需的信息
		super()._init_(make,model,year)		
#super()将父类和子类关联起来,
#调用父类的方法_init_()让ElectricCar实例包含父类的所有属性
		self.battery_size=70	#子类特有的属性

class ElectricCar(Car):
	def fill_gas_tank(self):	
#对于父类的方法,只要它不符合子类模拟的实物的行为,都可对其重写。
#可在子类中定义一个方法与要重写的父类方法同名。
#这样,python将不会考虑这个父类方法,而只关注在子类中定义的相应方法
		print("This car doesn't need a gas tank!")


class Battery():
	def __init__(self,battery_size=70):
		self.battery_size=battery_size
	def describe_battery(self):
		do something
class ElectricCar(Car):
	def __init__(self,make,model,year):
		super()._init_(make,model,year)
		self.battery=Battery()			#将实例作为属性	
my_tesla=ElectircCar('tesla','model s',2016)
my_tesla.battery.describe_battery()

导入类:

#car.py文件:
class Car():
	do something

#my_car.py文件:
from car import Car		#从模块中导入单个类

#car.py文件:
class Car():		#在一个模块中存储多个类
	do something
class Battery():
	do something
class ElectricCar(Car):
	do something

#my_electric_car.py文件:
from car import ElectricCar

#my_cars.py文件:
from car import Car,ElectricCar		#在一个模块中导入多个类

#my_cars.py文件:
import car		#导入整个模块
my_beetle=car.Car('volkswagen','beetle',2016)	
#使用句点表示法访问需要的类

from modeule_name import*	#导入模块中的所有类


#electric_car.py文件
from car import Car			#在一个模块中导入另一个模块
class Battery():
	do something
class ElectricCar(Car):
	do something

5.文件:

从文件中读取数据:

读取文本文件时,python将其中的所有文本都解读为字符串。若读取的是数字,并要将其作为数值使用,就必须使用函数int() 或 float()进行类型转换
读取整个文件:

with open('pi_digits.txt') as file_object:		
#读取txt文件,函数open()接受一个参数:要打开的文件名称,
#python在当前执行的文件所在的目录中查找指定的文件,
#函数open()返回一个表示文件的对象,关键字with在不再需要访问文件后将其关闭。
	contents=file_object.read()		
#read()读取这个文件的全部内容,
#并将其作为一个长长的字符串存储在变量contents中
	print(contents)		
	#输出最后会有一个空行,
	#因为read()到达文件末尾时返回一个空字符串,
	#而将这个空字符串显示出来就是一个空行
	print( contents.rstrip() )		#rstrip()可删除字符串末尾的空白

使用文件路径:

with open('text_files\filename.txt') as file_object:
#使用相对文件路径,该位置是相对于当前运行的程序所在目录的

file_path='C:\Users\ehmatthes\other_files\text_files\filename.txt'
with open(file_path) as file_object:	#使用绝对路径

逐行读取:

filename='pi_digits.txt'
with open(filename) as file_object:
	for line in file_object:		#利用for循环遍历文件中的每一行
		print(line)		
		#每行的末尾都有一个换行符,输出存在空白行,
		#若需消除空白行,使用rstrip()

创建一个包含文件各行内容的列表:

filename='pi_digits.txt'
with open(filename) as file_object:
	lines=file_object.readlines()	
	#readlines()从文件中读取每一行,并将其存储在一个列表中
for line in lines:
	print(line.rstrip())

使用文件的内容:

filename='pi_30_digits.txt'
with open(filename) as file_object:
	lines=file_object.readlines()
pi_string=''
for line in lines:
	pi_string+=line.strip()

写入文件:

写入空文件:
要将文本写入文件,在调用open()时需提供另一个实参,告知python要写入打开的文件
Python只能将字符串写入文本文件,要将数值数据存储到文本文件中,须先使用str()将其转换为字符串格式

filename='programming.txt'
with open(filename,'w') as file_object:		
#调用open时提供了两个实参,第一个实参为要打开的文件名称;
#第二个实参('w')表示要以写模式打开这个文件。
#( 读模式'r',附加模式'a',读写模式'r+' ,
#若省略模式实参,将以默认的只读模式打开文件)
#若要写入的文件不存在,函数open()将自动创建它。
#以写入'w'模式打开文件时,若指定的文件已存在,将在返回文件对象前清空该文件
	file_object.write("I love programming.")

写入多行:

filename='programming.txt'
with open(filename,'w') as file object:
	file_object.write("I love programming.\n")	
	#要让每个字符串都单独占一行,需在write()语句中包含换行符
	file_object.write("I love creating new games.\n")

附加到文件:
若需给文件添加内容,而不是覆盖原有的内容,可以附加模式打开文件。以附加模式打开文件时,python不会在返回文件对象前清空文件,而写入到文件的行都将添加到文件末尾。若指定的文件不存在,将创建一个空文件

with open(filename,'a') as file_object:

存储数据:

使用模块json来存储数据
模块json能将简单的python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据

使用json.dump()和json.load():
函数json.dump()接受两个实参:要存储的数据以及可用于存储数据的文件对象

#number_writer.py文件
import json
numbers=[2,3,5,7,11,13]
filename='numbers.json'
with open(filename,'w') as f_obj:
	json.dump(numbers,f_obj)

#number_reader.py文件
import json
filename='numbers.json'
with open(filename) as f_obj:
	numebrs=json.load(f_obj)	#使用json.load()将列表读取到内存中
print(numbers)

保存和读取用户生成的数据:

#remember_me.py文件
import json
username=input("What is your name? ")
filename='username.json'
with open(filename,'w') as f_obj:
	json.dump(username,f_obj)

#greet_user.py文件
import json
filename='username.json'
with open(filename) as f_obj:
	username=json.load(f_obj)

猜你喜欢

转载自blog.csdn.net/qq_44709990/article/details/105898918
今日推荐