今天把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)]

python的用途和组成_Python 用法总结相关推荐

  1. python help函数怎么用_python help函数实例用法

    有些人说py中有两个函数可以实现对所有函数的了解以及使用,其中之一,就是我们今天要讲解的help函数.有些小伙伴可能比较陌生,但是另一个函数是dir函数,这样是不是就能搞懂了.两者一定是跟查询有关的, ...

  2. python里else中文意思_Python循环语句中else的用法总结

    前言 本文讨论Python的for-else和while-else等语法,这些是Python中最不常用.最为误解的语法特性之一. Python中的for.while等循环都有一个可选的else分支(类 ...

  3. python中index什么意思_Python中index()和seek()的用法(详解)

    1.index() 一般用处是在序列中检索参数并返回第一次出现的索引,没找到就会报错,比如: >>> t=tuple('Allen') >>> t ('A', 'l ...

  4. python scatter参数详解_Python中scatter函数参数及用法详解

    最近开始学习Python编程,遇到scatter函数,感觉里面的参数不知道什么意思于是查资料,最后总结如下: 1.scatter函数原型 2.其中散点的形状参数marker如下: 3.其中颜色参数c如 ...

  5. python中内置函数的用法_python中str内置函数用法总结

    大家在使用python的过程中,应该在敲代码的时候经常遇到str内置函数,为了防止大家搞混,本文整理归纳了str内置函数.1字符串查找类:find.index:2.字符串判断类:islower.isa ...

  6. python kwargs是什么参数_Python中*args 和 **kwargs的用法总结

    对于大部分Python新手来说,*args和**kwargs这两个魔法变量需要花大量的时间来解释.那么它们到底是什么呢?在什么时候使用它们呢?要搞清楚这些问题,首先你要明白,其实并不是必须写成*arg ...

  7. python字符串strip的作用_Python字符串函数strip()原理及用法详解

    Python字符串函数strip()原理及用法详解 strip:用于移除字符串头尾指定的字符(默认为空格)或字符序列.注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符. 语法:str.s ...

  8. python scatter参数详解_Python 中 scatter 函数参数及用法详解

    Python 中 scatter 函数参数及用法详解 Python 中 scatter 函数参数及用法详解 这里有新鲜出炉的 Python 教程, 程序狗速度看过来! Python 编程语言 Pyth ...

  9. python可以引流吗_python能干嘛?你所不知道的Python有趣用途(上)

    前言 很多人都觉得Python虽然好学,但却不晓得如何将其应用到生活中,或是只知道Python可以拿来做「数据分析」.「爬虫」.甚至是「人工智慧」,但却觉得那些东西离自己很遥远 (尤其是初学者,经常会 ...

最新文章

  1. RxJava 内置多种用于调度的线程类型
  2. python字符串注释_python字符串注释_Python学习笔记-字符串与注释
  3. Word:段前空行不显示问题解决办法
  4. destoon 屏蔽会员组,让个人,游客不显示
  5. 通过流进行字符集编码转换
  6. javaone_JavaOne演讲者选择了您不容错过的10个会话
  7. 拓端tecdat|Matlab马尔可夫区制转换动态回归模型估计GDP增长率
  8. php课设报告致谢_奇安信CERT发布1月安全监测报告:需警惕这19个高危漏洞
  9. Pycharm安装与汉化教程
  10. JS 字符串去除首尾空格
  11. H5唤起APP客户端
  12. 3d公式算法计算机,最新3d万能计算定胆公式来了
  13. CATIA二次开发开源项目—CATSearch
  14. plt 字体 times new roman Ubuntu添加windows启动项
  15. 从黄金时代到没落尽头,“寻求出售”的GoPro遭遇了什么?
  16. AIS(ACL,IJCAI,SIGIR)(2019)论文报告会,感受大佬的气息...
  17. android 切换摄像头加动画,android前后摄像头切换
  18. Spring的初始化和对象创建流程
  19. PHP-邮件发送接口
  20. Cordova 环境搭建+打包Android APK

热门文章

  1. [日更-2019.3.31]如何下载Nexus5的LineageOS14.1(cm-14.1)系统源码并编译、刷机
  2. -atime、-ctime、mtime、-newer
  3. Nature | 基于细菌构建具有类真核细胞结构和功能的人工细胞
  4. 黑龙江省大庆市谷歌高清卫星地图下载
  5. css绝对定位如何居中?css绝对定位居中的四种实现方法-web前端教程
  6. 【技术分享】ApolloEDU6.0+LGSVL联合仿真环境搭建
  7. c语言蚂蚁搬,关于蚂蚁搬食的作文
  8. 如何在物联网平台创建一个千里传音产品?
  9. 教师资格证考69分是怎么算的?
  10. java.sql.SQLException: The connection property ‘zeroDateTimeBehavior‘ acceptable values are: ‘CONVER