python from函数用法_Python 用法总结

今天把Python的基础用法回顾了一遍,感觉要想真正掌握还是得运用。只有你自发性在projects和题目中想到运用哪个数据结构,哪个模块, 这样知识才是最牢固的。基础知识整理如下:

基础数据结构

字符串

name = 'Qiao'

age = '23'

print name + '-' + age

Qiao-23

%s 格式化string

str1 = "my name is%s, and I'm%syears old" % ('Qiao', '23')

print str1

my name is Qiao, and I'm 23 years old

数值型

# int

age = 50

#float

earning = 3.60

容器

掌握:如何定义容器,如何进行4个操作:增,删,查询,修改

List

patientList = ['Qiao', 'Ma', 'Jenny']

print 'The number of patients:', len(patientList)

The number of patients: 3

# 1) add

patientList.append('Lu')

print 'The number of patients:', len(patientList)

The number of patients: 4

# 2) delete

del patientList[0]

print 'after discharging the first patient:', patientList

patientList.remove('Jenny')

print 'keep discharging the next patient:', patientList

after discharging the first patient: ['Ma', 'Jenny', 'Lu']

keep discharging the next patient: ['Ma', 'Lu']

# 3) edit

print 'before editting, the first ele is:', patientList[0]

patientList[0] = 'Wang'

print 'after editting, the first ele is', patientList[0]

before editting, the first ele is: Ma

after editting, the first ele is Wang

Tuple

DontChange = ('Tecent', 'Alibaba', 'Apple', 'Google', 'MicroSoft')

print 'Length', 'Len(DontChange)'

# find a certain ele, index begining from 0

print 'The 1st ele is', DontChange[0]

Length Len(DontChange)

The 1st ele is Tecent

Set

Dedup = {'Tecent', 'Alibaba', 'Apple', 'Google', 'MicroSoft', 'Tecent'}

print Dedup

set(['Tecent', 'Google', 'Apple', 'MicroSoft', 'Alibaba'])

# 1) initiate and add ele

stockSets = set()

stockSets.update(['Tecent', 'Alibaba', 'JD'])

print stockSets

set(['JD', 'Tecent', 'Alibaba'])

# 2) del

stockSets.discard('JD')

print stockSets

set(['Tecent', 'Alibaba'])

# 3) find

print 'DouYing' in stockSets

print 'Alibaba' in stockSets

False

True

# 4) edit

#stockSets.discard('JD')

stockSets.update('JDdd') ## UPDATE!!!!!!!!

stockSets.update(['JD'])

print stockSets

set(['d', 'J', 'Alibaba', 'JD', 'Tecent', 'D'])

Dictionary

patientDic = {'001':'Qiao', '002': 'Lisa', '003':'Han lin', '004':'Hua'}

patientDic2={'001':['aa',29,'First Type','Bad'],

'002':['bb',34,'Second Type','Better']}

print patientDic2

{'002': ['bb', 34, 'Second Type', 'Better'], '001': ['aa', 29, 'First Type', 'Bad']}

patientDic2['005']=['Ketty',30,'First Type','Better']

print(patientDic2)

{'002': ['bb', 34, 'Second Type', 'Better'], '001': ['aa', 29, 'First Type', 'Bad'], '005': ['Ketty', 30, 'First Type', 'Better']}

# find

value = patientDic2['001']

print value

# edit

print ('before editting', patientDic2['001'])

patientDic2['001'] = ['Adela',29,'First Type','Better']

print ('after editting', patientDic2['001'])

('before editting', ['aa', 29, 'First Type', 'Bad'])

('after editting', ['Adela', 29, 'First Type', 'Better'])

If-Else

scoreName = 9.1

if scoreName >= 8:

print 'I want to watch this movie'

else:

print 'It stinks, pass it'

'''边界条件:逻辑判断'''

#定义列表:病人姓名

nameList=['Lucy','Kun','Jianlin','Hua']

if 'Lucy' not in nameList:

print('No person named Lucy')

else:

print("It's in the patient list")

It's in the patient list

'''多个条件判断'''

age=int(input('Age of the dog?:'))

if age < 0 :

print("Age can't be less than 0")

elif age == 1:

print('eqvivalent to 14-year-old human')

elif age == 2 :

print('eqvivalent to 22-year-old human')

else:

human=22+(age-2)*5

print('eqvivalent to human age',human)

QWdlIG9mIHRoZSBkb2c/77ya

4

('eqvivalent to human age', 32)

Rrcursion

#容器:1天中吃第几次饭

eatList=['First Meal','Second Meal','Third Meal']

#循环

for i in eatList:

print(i)

案例2:清洗GAFATA股票数据

'''定义字典:6家公司(GAFATA)的股票key是公司名称,value是股票代码'''

gafataDict={'Google':'Goog','Amazon':'aMZN','Facebook':'FB',

'Apple':'aapl','Alibaba':'BABA','Tencent':'0700'}

#将股票代码全部大写

for key,value in gafataDict.items():

#对股票代码转换成大写

newValue=value.upper()

#将转换后新的股票代码赋值给对应的key

gafataDict[key]=newValue

print(gafataDict)

{'Google': 'GOOG', 'Apple': 'AAPL', 'Alibaba': 'BABA', 'Amazon': 'AMZN', 'Tencent': '0700', 'Facebook': 'FB'}

continue用于跳出当前循环

for key,value in gafataDict.items():

if(key=='Apple'):

continue

print('Current Compnay:',key,',Stock Code:',value)

('Current Compnay:', 'Google', ',Stock Code:', 'GOOG')

('Current Compnay:', 'Alibaba', ',Stock Code:', 'BABA')

('Current Compnay:', 'Amazon', ',Stock Code:', 'AMZN')

('Current Compnay:', 'Tencent', ',Stock Code:', '0700')

('Current Compnay:', 'Facebook', ',Stock Code:', 'FB')

break用于退出整个循环

#查找苹果公司的股票代码

number=0

for key,value in gafataDict.items():

number=number+1

if(key=='Apple'):

print('Find:',key,'Stock Code:',value)

break

print('Find:',key,',Stock Code:',value)

('Find:', 'Google', ',Stock Code:', 'GOOG')

('Find:', 'Apple', 'Stock Code:', 'AAPL')

函数

如果函数是字符串,元祖和数字这三种不可更改的对象,参数传递时,相当于传递的是复制出来的数据,对于数据本身没有影响

如何自定义函数?

def add(x,y):

z=x+y

return z

#使用函数

a=1

b=2

c=add(x=a,y=b)

print('1和2相加等于',c)

#定义函:改变数据的值

def changeInt(a):

a=a+1

'''使用函数参数是不可变数据类型(字符串,元祖,数值):传递的只是该数据类型的值(相当于复制一份)'''

b=1

print('Before calling the function=',b)

changeInt(a=b)

print('After calling the function=',b)

('Before calling the function=', 1)

('After calling the function=', 1)

函数参数:可变数据类型

#定义函:改变列表的值

def changeList(inputList):

inputList.append('Lisa')

'''使用函数参数是可变数据类型:传递的是该变量的引用地址'''

nameList=['Han','Arm']

print('Before calling the function:',nameList)

changeList(inputList=nameList)

print('After calling the function:',nameList)

('Before calling the function:', ['Han', 'Arm'])

('After calling the function:', ['Han', 'Arm', 'Lisa'])

变量作用域

定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域。 局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问。

#变量作用域

def test():

aStr='别理会他人闲言闲语,今日随他们,让他们说吧,你的机会将会到来,再来证明自己。'

#在函数外面,访问函数内的局部变量aStr

print(aStr)

模块

如何导入模块

Import 包 import 包 as 别名 from 包 import 函数名

from collections import deque # 只引入collections 中deque 这一个包

数据结构

collections 中有很多有用的高级数据结构 1. 双向链表queue: 队列,栈 2. 排序字典: OrderedDict 3. 计数器 Counter

## Queue (deque)

from collections import deque

#定义队列:排队吃饭人的编号

queue = deque(['001','002','003','04','005'])

#入队:在队列尾部插入元素

queue.append('006')

print(queue)

#出队:在队列头部删除元素

queue.popleft()

print(queue)

Stack

栈这种数据结构有点像像生活中的木桶。你往栈中加入新的元素,就是入栈,新的元素总是放在木桶的最上面。

#定义栈:浏览我个人知乎主页的顺序

stack=deque(['Zhu hu feed','Zhi hu Questions','Zhihu Articles'])

print(stack)

---------------------------------------------------------------------------

NameError Traceback (most recent call last)

in ()

1 #定义栈:浏览我个人知乎主页的顺序

----> 2 stack=deque(['Zhu hu feed','Zhi hu Questions','Zhihu Articles'])

3 print(stack)

NameError: name 'deque' is not defined

#入栈:在栈顶加入元素

stack.append('Zhihu feature')

print(stack)

#出栈:将栈顶元素移除

stack.pop()

print(stack)

排序字典OrderedDict

'''OrderedDict:按照插入key的顺序,对字典排序'''

from collections import OrderedDict

#定义有序字典

gafataDict={'Google':'Goog','Amazon':'aMZN','Facebook':'FB',

'Apple':'aapl','Alibaba':'BABA','Tencent':'0700'}

gafataDict

{'Alibaba': 'BABA',

'Amazon': 'aMZN',

'Apple': 'aapl',

'Facebook': 'FB',

'Google': 'Goog',

'Tencent': '0700'}

计数器Counter

'''计数器'''

from collections import Counter

cDict = Counter("Some birds aren't meant to be caged that's all Their feathers are just too bright Feathers too bright".split())

print cDict

Counter({'bright': 2, 'too': 2, 'meant': 1, 'be': 1, 'all': 1, 'just': 1, 'Their': 1, 'caged': 1, 'Feathers': 1, 'Some': 1, 'to': 1, 'feathers': 1, 'are': 1, "aren't": 1, 'birds': 1, "that's": 1})

cDict['bright']

2

#出现次数最多的3个词

cDict.most_common(3)

[('too', 2), ('bright', 2), ('meant', 1)]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值