学python

时间:2024-10-19 13:03:32

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