学python
1.*和**
def sum(*x):
ans=0
for i in x:
ans+=i
return ans
def haha(one,two):
print(one,' ',two)
print(sum(1,2,3,4))
haha(**{"one":1,"two":2})
10 1 2
2.zip
x=["one","two","three"] y=zip(x) print(type(y)) print(list(y)) print(list(y))#输出为空,zip只能用一次 print(tuple(zip(x,x))) print(dict(zip(x,(1,2)))) print(dict(zip(x,[1,2,3,4]))) #len(dict(zip(key,vlaue)))=min(len(key),len(value)) print(list(zip(x,x,x))) print(dict(zip(x,x,x)))#报错,dict只能处理二元组
Traceback (most recent call last):
File "C:/Users/weidiao/Documents/PycharmProjects/python实验室/main2.py", line 11, in <module>
<class 'zip'>
print(dict(zip(x,x,x)))#报错,dict只能处理二元组
[('one',), ('two',), ('three',)]
ValueError: dictionary update sequence element #0 has length 3; 2 is required
[]
(('one', 'one'), ('two', 'two'), ('three', 'three'))
{'two': 2, 'one': 1}
{'two': 2, 'three': 3, 'one': 1}
[('one', 'one', 'one'), ('two', 'two', 'two'), ('three', 'three', 'three')]
3.print
print(1,2,3)#逗号隔开若干个数全部输出
print("one is %d"%1,"two is %d"%2)
print("one is %d ,two is %d"%(1,2))
print("one is {one},two is {two}".format(**{"one":1,"two":2}))
print("one is {0},two is {1}".format(1,2))
print("one is {},two is {}".format(1,2))
print('{name}网址: {site}'.format(name='菜鸟教程', site='www.runoob.com'))
print("one is {0[one]},two is {1[two]}".format({"one":1},{"two":2}))
1 2 3 one is 1 two is 2 one is 1 ,two is 2 one is 1,two is 2 one is 1,two is 2 one is 1,two is 2 菜鸟教程网址: www.runoob.com one is 1,two is 2
4.abs和fabs
abs是buit_in函数,fabs是math模块的函数,故fabs需要引入math module才能使用.abs会调用fabs.二者效果并无分别.
5.python中的property
property(fget=None, fset=None, fdel=None, doc=None) -> property attribute
fget is a function to be used for getting an attribute value, and likewise
fset is a function for setting, and fdel a function for del'ing, an
attribute. Typical use is to define a managed attribute x:
class C(object):
def getx(self): return self._x
def setx(self, value): self._x = value
def delx(self): del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
Decorators make defining new properties or modifying existing ones easy:
class C(object):
@property
def x(self):
"I am the 'x' property."
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
安装ipython,使用cmder,输入property?,就会看到以上内容.
定义property有两种方式,一种是使用class property,它位于builtin,是一种class.另一种方式是使用注解.
下面测试一下,是否真的调用了setter和getter
class haha:
def __init__(self):
self.__x='weidiao'
@property
def x(self):
print("x.property")
return self.__x
@x.getter
def x(self):
print("x.getter")
return self.__x
@x.setter
def x(self,x):
print("x.setter")
self.__x=x
@x.deleter
def x(self):
print('x.deleter')
del self.__x
a=haha()
print(a.x)
a.x='haha'
print(a.x)
del a.x
print(a.x)
输出为
x.getter
weidiao
x.setter
x.getter
haha
x.deleter
x.getter
Traceback (most recent call last):
File "C:/Users/weidiao/Documents/PycharmProjects/python实验室/main2.py", line 25, in <module>
print(a.x)
File "C:/Users/weidiao/Documents/PycharmProjects/python实验室/main2.py", line 11, in x
return self.__x
AttributeError: 'haha' object has no attribute '_haha__x'
6.python之禅
IDLE中输入import this即可看见python之禅,其中包含了python的许多信条,我认为这些是十分重要的原则,对于理解python至关重要.其他的是技,这才是道.
The Zen(禅) of Python, by Tim Peters Beautiful is better than ugly.美丽胜丑陋, Explicit is better than implicit.清晰胜模糊, Simple is better than complex.简易胜复杂, Complex is better than complicated.复杂胜杂乱, Flat is better than nested.单层比嵌套(python中没有嵌套类), Sparse is better than dense.稀疏胜稠密, Readability counts.可读性至重, Special cases aren't special enough to break the rules.特殊很少用(不因为追求完善而损害简易性), Although practicality beats purity.纵使实践胜理论, Errors should never pass silently.错误不静默, Unless explicitly silenced.除非特意说(除非特意说明让错误静默). In the face of ambiguity, refuse the temptation to guess.不乱猜模糊(避免歧义,对于歧义拒绝猜测,避免晦涩), There should be one-- and preferably only one --obvious way to do it.至理一足矣(用最明显的方法去做事). Although that way may not be obvious at first unless you're Dutch.纵使不明显(尽管一开始这种方法并不明显). Now is better than never.现在胜永不(凡事要着手做), Although never is often better than *right* now.纵使永不胜过立即(宁可永远不做也不要草率决定). If the implementation is hard to explain, it's a bad idea.难言之理必有不足(真理总是简单易于描述的). If the implementation is easy to explain, it may be a good idea.易行之事方为妙策(好主意总是容易实现). Namespaces are one honking great idea -- let's do more of those!命名空间真是好法.
查看一下this模块的代码
s = """Gur Mra bs Clguba, ol Gvz Crgref
Ornhgvshy vf orggre guna htyl.
Rkcyvpvg vf orggre guna vzcyvpvg.
Fvzcyr vf orggre guna pbzcyrk.
Pbzcyrk vf orggre guna pbzcyvpngrq.
Syng vf orggre guna arfgrq.
Fcnefr vf orggre guna qrafr.
Ernqnovyvgl pbhagf.
Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf.
Nygubhtu cenpgvpnyvgl orngf chevgl.
Reebef fubhyq arire cnff fvyragyl.
Hayrff rkcyvpvgyl fvyraprq.
Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff.
Gurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg.
Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu.
Abj vf orggre guna arire.
Nygubhtu arire vf bsgra orggre guna *evtug* abj.
Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.
Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.
Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!"""
d = {}
for c in (65, 97):
for i in range(26):
d[chr(i+c)] = chr((i+13) % 26 + c)
print("".join([d.get(c, c) for c in s]))
还是加密的一段文字,只加密了52个英文字母,对于其他字符还用原来的.dic.get(c1,c2)表示如果没有c1对应的值,就用c2代替.加密方法用的是平移法加密,每个字母用它后面的第13个字母代替.import this然后print(this.d)可以查看字符对照表.'a'对应'n','b'对应'o'...
7.python中的列表推导式
列表推导式非常重要,它能够减少大量代码,将2~3行的工作量压缩为一行来实现,并且可读性很好,一定要学会.
In [2]: a=[1,2,3]In [3]: [a[i]for i in range(len(a)-1,-1,-1)if i%2]#注意for循环倒序数组写作range(len(a)-1,-1,-1);注意python中的if后面可以跟int值,python对于bool要求并不严格 Out[3]: [2]
a=[1,2,3] b=[4,5,6] In [10]: [a[i]*b[j] for i in range(len(a)) for j in range(len(b))] Out[10]: [4, 5, 6, 8, 10, 12, 12, 15, 18] In [16]: [a[i]*b[j] for i in range(len(a)) if i>1 for j in range(len(b)) if j==1 if i<3] Out[16]: [15]
在每一个for后面都跟若干个if来过滤for中的变量,多个if是and的关系,一个失败了就不在往下执行,if的位置很随意,只要能找到变量就可以.
其实,只要明白列表推导式的原理就可以了,上面In[16]相当于
ans=[]#定义列表
for i in range(len(a)):
if i>1:
for j in range(len(b)):
if j==1:
if i<3:
ans.append(a[i]*b[j])
可见,将if尽量上提效率比较高.
8.python变量作用域
for i in range(2):
for i in range(2):
print(i)
正常运行不报错,输出0,1,0,1每个字符一行.
python中的变量标识符形成一个链,从当前作用域从里往外找,直到找到为止,并不影响其它的.在java中就不允许这么嵌套定义,会报错重定义变量i.python的原则就是把编译器实现的简单一些,将权力交给程序员,因为这样不仅实现简单,而且显然易见.比如我问你print(i)里的i是哪一个?很显然正常人都会认为是第二个.因为python变量作用域的这种特性,我们无需定义for i,j,k,p,q,m...只要是与外层无关的东西,就可以继续for i,j,而不用思考应该用什么变量名.
9.python判断字符串包含
python的str对象并不包含contains()函数来判断包含,但python有好几种其它方法来实现是否包含子串.
(1)'id' in 'weidiao':使用in关键字来判断
(2)"weidiao".find('id'):如果不存在返回-1,如果存在,返回位置
(3)"weidiao".index('id'):如果不存在抛出异常,所以需要写成:
def find_string(s,t):
try:
s.index(t)
return True
except(ValueError):
return False
(4)"weidiao".count("id"):统计个数
(5)import string,然后使用string模块的find(),rfind(),index(),rindex()等函数,这跟直接使用str类型的成员函数没啥区别.
10.request模块
response返回类型有:resp.text(文本类型,str),resp.content(二进制类型,byte[]),resp.json(json类型,dic).在使用resp.text时,可以通过resp.encoding="utf8"来设置文本编码.下面从beetl网站上爬取一些程序员福利,beetl是一个java网页模板引擎.
import requests
from bs4 import BeautifulSoup
home="http://ibeetl.com/community/?/sort_type-new__category-7__day-0__is_recommend-0__page-"
counter=0
for i in range(1,4):
url=home+str(i)
resp=requests.get(url)
resp.encoding="utf8"
soup=BeautifulSoup(resp.text,)
a=soup.select("a")
for j in a:
if '福利' in j.text and j.text!="程序员福利":
resp=requests.get(j['href'])
soup=BeautifulSoup(resp.text)
img=soup.select(".mod-body img")
resp=requests.get(img[0]['src'])
f=open("img{}.jpg".format(counter),"wb")
f.write(resp.content)
counter+=1
学python的更多相关文章
- 【Python五篇慢慢弹】快速上手学python
快速上手学python 作者:白宁超 2016年10月4日19:59:39 摘要:python语言俨然不算新技术,七八年前甚至更早已有很多人研习,只是没有现在流行罢了.之所以当下如此盛行,我想肯定是多 ...
- <-0基础学python.第一课->
初衷:我电脑里面的歌曲很久没换了,我想听一下新的歌曲,把他们下载下来听,比如某个榜单的,但是一首一首的点击下载另存为真的很恶心 所以我想有没有办法通过程序的方式来实现,结果还真的有,而且网上已经有有人 ...
- 学Python后到底能干什么?
Python是一种什么语言? Python是一种计算机程序设计语言.你可能已经听说过很多种流行的编程语言,比如非常难学的C语言,非常流行的Java语言,适合初学者的Basic语言,适合网页编程的Jav ...
- 关于智普 - 千人免费学|Python培训|国内最权威python培训|html5
关于智普 - 千人免费学|Python培训|国内最权威python培训|html5 智普教育隶属于北京顶嵌开源科技有限公司,成立于2008年. 智普开源是基于Linux系统的互联网开源学习平台,讲求务 ...
- [置顶] 和孩子们一起学Python编程
1. 推荐书名 Computer Programming for Kids and Other Beginners in Python, 4Ed.pdf 中文译名:<和孩子们一起学Pyt ...
- 简学Python第二章__巧学数据结构文件操作
#cnblogs_post_body h2 { background: linear-gradient(to bottom, #18c0ff 0%,#0c7eff 100%); color: #fff ...
- 简学Python第一章__进入PY的世界
#cnblogs_post_body h2 { background: linear-gradient(to bottom, #18c0ff 0%,#0c7eff 100%); color: #fff ...
- 一步一步学Python(2) 连接多台主机执行脚本
最近在客户现场,每日都需要巡检大量主机系统的备库信息.如果一台台执行,时间浪费的就太冤枉了. 参考同事之前写的一个python脚本,配合各主机上写好的shell检查脚本,实现一次操作得到所有巡检结果. ...
- 为什么要学Python
人生苦短,我用python.在大学四年的本科学习中,Python是我接触过语法最简单,功能最为强大的语言,拥有众多第三方库的支持的语言.如果要选一门编程语言作为入门,建议使用Python.但是为了更加 ...
- C语言老司机学Python (五)
今天看的是标准库概览. 操作系统接口: 用os模块实现. 针对文件和目录管理,还有个shutil模块可以用. 例句: import os os.getcwd() # 返回当前的工作目录 os.chdi ...
随机推荐
- 3D banner(CSS3+HTML5)
1.这是一篇 3Dbanner制作的简易流程,支持高版本的chrome和firefox浏览器,俩浏览器显示可能会有些差异 2.没有兼容性代码,因为仅仅只是熟悉流程,希望小伙伴们自己改善哈(>﹏& ...
- SharePoint 2013 自定义扩展菜单
在对SharePoint进行开发或者功能扩展的时候,经常需要对一些默认的菜单进行扩展,以使我们开发的东西更适合SharePoint本身的样式.SharePoint的各种功能菜单,像网站设置.Ribbo ...
- 【Swift】 应用内显示 AppStore 某个应用的详情
前言 应用内跳转到 AppStore 的文章很多,一般都是用 SKStoreProductViewController 来实现的,不知道有没有在意一个问题:打开很慢!!怎么忍?! 声明 欢迎转载,但请 ...
- Git Learning - By reading ProGit
Today I begin to learn to use Git. I learn from Pro Git. And I recommend it which is an excellent bo ...
- Play Framework 完整实现一个APP(十一)
添加权限控制 1.导入Secure module,该模块提供了一个controllers.Secure控制器. /conf/application.conf # Import the secure m ...
- jQuery插件库代码分享 - 进阶者系列 - 学习者系列文章
这些天将原来在网上找的jQuery插件进行了下整理,特此将代码分享出来给大家. 见下图结构. 对目录结构进行了分类.这里是插件列表. 这里总共收集了20来个插件.还有下面未进行划分的. 下面是DEMO ...
- Vmware扩展磁盘如何不需重启系统
在虚拟机Vmware中我们有时候需要添加新的虚拟磁盘或给已有虚拟磁盘扩容(expand),在新增磁盘或磁盘扩容后,Linux系统并不能马上识别到.也就是说你看不到磁盘空间变化(使用fdisk -l查看 ...
- Function.prototype.call 和 Function.prototype.apply 的区别
call和apply函数是function函数的基本属性,都可以用于更改函数对象和传递参数,是前端工程师常用的函数.具体使用方法请参考以下案列: 例如: 申明函数: var fn = function ...
- MongoDB学习笔记~数据结构与实体对象不一致时,它会怎么样?
回到目录
- Mysql有用的面试题
A.一道SQL语句面试题,关于group by表内容:2005-05-09 胜2005-05-09 胜2005-05-09 负2005-05-09 负2005-05-10 胜2005-05-10 负2 ...