基础知识汇总

基础知识汇总
1.self
   首先明确的是self只有在类的方法中才会有,独立的函数或方法是不必带有self的。self在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数。self名称不是必须的,在python中self不是关键词,你可以定义成a或b或其它名字都可以,但是约定成俗,不要搞另类,大家会不明白的。

python中的self就相当于C++中的this指针
也就是指向对象本身的指针
self.name = name 就是当前对象的成员变量name赋值为name。
在这里面self.name是什么类型呢?和变量有什么不同?
python的特性就是声明一个变量的时候不需要手动的指定类型,赋值的时候类型就自动的决定了,并且后期也可以改变。这里name是从外部传入的,所以这里的self.name的类型就是由外部传递的name类型决定的。

那就是说self就是实例。name就是它的一个属性了。

2.super
Python 的内置函数 super 来调用父类 Parent 里的版本

3.类参数不用写在类名后,在init里加。

4.函数参数可以设置默认值,但只能放在最后,如:
def say(message, times = 1):
    print message * times

say('Hello')
say('World', 5)

5.列表、元组中一个元素 my[0],字典是my['index']

6.b=a 如果a列表中数据改变,那么b列表中数据也改变

7.函数接收参数,如果函数中参数写为*args,所有多余的函数参数都会作为一个元组存储在args中;**args,多余的参数则会被认为是一个字典的键/值对。

8.enumerate 显示索引和值
>>> for a, b in enumerate(['a','b','c']):
...     print a , b
...
0 a
1 b
2 c

9.id 显示内存地址,判断对象是否变化

10.正则
?  单独出现表未左边字符出现0或1次,左边为重复元字符表示越短越好如:(+?) 贪婪模式

11.a,b=b,a+b
可以拆成
a = b, b = a + b
也就是说等号左边的第一个位置的等于等号右边的第一个位置
等号左边第二个位置的等于等号右边第二个位置的。
(a, b) =  (b, a + b)
如何写成a=b
             b=a+b 这样a的值就变了,(a, b) =  (b, a + b) 相当于a用原来的值

12.yield
函数只有返回一个值,每次都一样,而且使用yield生成器,可以用for 循环来取,每次都不一样,也就是说yield b 返回的值是一个循环
def fab(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        # print b
        a, b = b, a + b
        n = n + 1

i=fab(5)
for a in i:
    print a

13.元组中包含的列表是可以改变的
>>> a=(['a','b'], 'c', 'd')
>>> a[0][0] = '1'
>>> a
(['1', 'b'], 'c', 'd')

14.列表浅拷贝和深拷贝
>>> l = [ [1,2],3]
>>> s = l[:]          --同s=l
>>> s[0][0]=5
>>> s
[[5, 2], 3]
>>> l
[[5, 2], 3]

--深
>>> a=[1,2,3]
>>> b=a[::]
>>> b[0]=5
>>> b
[5, 2, 3]
>>> a
[1, 2, 3]

15.字典的格式打印
>>> dict
{'arch': 'sunos5', 'name': 'venus', 'port': 80}
>>> print 'host %(name)s is running on port %(port)d' %dict
host venus is running on port 80

16.os.system('ipconfig') 执行系统命令

17. small = x if x < y else y
同于
if x < y :
    small = x
else:
    small = y

18.zip()的使用
>>> l1 = ('a','b','c','d')
>>> l2 = (1,2,3,4)
>>> b = zip(l1,l2)
>>> b
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

>>> a=[[1, 2, 3],[4, 5, 6]]
>>> print zip(a)
[([1, 2, 3],), ([4, 5, 6],)]
参数解包
>>> print zip(*a)
[(1, 4), (2, 5), (3, 6)]

19. for...else语句中,break会跳过else

20. 文件的迭代访问
>>>myfile = open('1.txt')
>>>for eachline in myfile:
....    print eachline

for eachline in myfile 等同 for eachline in myfile.readlines()

21. 迭代统计文件字数
>>> f = open('b.txt')
>>> len([word for line in f for word in line.split( )])
62

22. 批量修改列表内字符
>>> all = [x.strip() for x in f.readlines()]

23.python 列表list中内置函数sort,sorted
sorted(a)                  #将a从小到大排序,不影响a本身结构
sorted(a,reverse = True)   #将a从大到小排序,不影响a本身结构
a.sort()                   #将a从小到大排序,影响a本身结构
a.sort(reverse = True)     #将a从大到小排序,影响a本身结构

#调用sorted()排序

dict = {"a" : "apple", "b" : "grape", "c" : "orange", "d" : "banana"}

print dict  

#按照key排序

print sorted(dict.items(), key=lambda d: d[0])

#按照value排序

print sorted(dict.items(), key=lambda d: d[1])

--------------------------------sorted---------------------------------------
>>> help(sorted)
Help on built-in function sorted in module __builtin__:

sorted(...)
    sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
---------------------------------sort----------------------------------------
>>> help(list.sort)
Help on method_descriptor:

sort(...)
    L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
    cmp(x, y) -> -1, 0, 1
-----------------------------------------------------------------------------

iterable:是可迭代类型;
cmp:用于比较的函数,比较什么由key决定,有默认值,迭代集合中的一项;
key:用列表元素的某个属性和函数进行作为关键字,有默认值,迭代集合中的一项;
reverse:排序规则. reverse = True 或者 reverse = False,有默认值。
返回值:是一个经过排序的可迭代类型,与iterable一样。
 
注;一般来说,cmp和key可以使用lambda表达式。

sort()与sorted()的不同在于,sort是在原位重新排列列表,而sorted()是产生一个新的列表。


24.函数中return的作用是函数立即返回,循环不再继续运行.
def fc(lst):
    for i in lst:
        if i >0:
            continue
        else:
            return i
l = [1, -1, 2, -3, -4, 6, 7]

print fc(l)
-1

25.关键字变量参数(字典类型)在非关键字变量参数之后
def newfoo(arg1, arg2, *arv, **argv):
    print 'arg1 is :', arg1
    print 'arg2 is :', arg2
    for each in arv:
        print 'tuple :', each

newfoo(arg1='1', arg2=3, 4, 5)
报错:SyntaxError: non-keyword arg after keyword arg
————因为字典类型应该在最后
 newfoo(4, 5, arg1='1', arg2=3)
报错:TypeError: newfoo() got multiple values for keyword argument 'arg1'
————因为arg1被赋了2个值4和1

26.lamda函数
def add(x, y):
    return x+y
print add(5, 9)
等同于
a = lambda x, y: x + y
print a(5, 9)

27.map函数
对集合使用函数,多个集合同时按顺序取1个出来处理,保存为列表
map(lambda x: x**2, range(6))
等同于
[x**2 for x in range(6)]

28.map 列表
a = map(lambda x, y: x + y, [1, 3, 5], [2, 4, 6])
print a
等同于
a = [x + y for x, y in zip([1, 3, 5] , [2, 4, 6])]
print a
执行结果: [3, 7, 11]

b = [x + y for x in [1, 3, 5]  for y in [2, 4, 6]]
print b
等同于
b = []
for x in [1, 3, 5]:
    for y in [2, 4, 6]:
       b.append(x + y)
print b
执行结果:[3, 5, 7, 5, 7, 9, 7, 9, 11]

30.reduce
对集合中前2个进行函数调用,返回值再和后面数调用函数,输入2个参数,返回1个数
a = reduce(lambda x, y: x + y, (0, 1, 2, 3, 4))
print a
结果:10

31.闭包
引用外部变量的内部函数是闭包closure
>>> def counter(start_at = 0):
...     count = [start_at]
...     def incr():
...         count[0] += 1
...         return count[0]
...     return incr
...
>>> count = counter(5)
>>> print count()
6
>>> print count()
7

32.递归函数
求n*(n-1)*...*1
def f(n):
    if n == 0 or n == 1:
        return 1
    else:
        return (n * f(n-1))
print f(50)

33.子类中如果写了构造器__init__,那就需要显式的写出父类的构造器

34.dir(c), c.__class__, c.__dict__

35.
>>> class myClass(object):
...     def __init__(self):
...         self.foo = 100
...
>>> myInst = myClass()
>>> hasattr(myInst, 'foo')
True
>>> getattr(myInst, 'foo')
100
>>> getattr(myInst, 'bar', 'oops!')    --oops为默认值,如果bar不存在就返回默认值
'oops!'
>>> setattr(myInst, 'bar', 'my attr')
>>> getattr(myInst, 'bar')
'my attr'
>>> delattr(myInst, 'foo')
>>> dir(myInst)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bar']
>>> hasattr(myInst, 'foo')
False
>>> myInst.__dict__
{'bar': 'my attr'}

36.__str__函数定义了 print classA 的输出值
__repr__定义了执行类实例的返回值
可以用__repr__ = __str__

37.exec执行py文件内容
f = open('1.py')
exec f
等同于
execfile('1.py')

38.eval(a)转换字符串为对象
>>> b = eval('dir()')
>>> b
['__builtins__', '__doc__', '__name__', '__package__', 'a', 'b']

39.字符串
>>> c = '%d %s %d = %d' % (5, 'add', 3, 8)
>>> c
'5 add 3 = 8'

40.字符串显示
>>> print '%03d' % 8
008

41.正则表达式 ?
1.单独使用表示0或1次.
2.紧跟在表示重复的元字符后,表示搜索引擎匹配的字符串越短越好

42.chcp 65001 设置CMD的编码为UTF-8

43.在python27/scripts下执行easy_install Tornado

44.url解码

>>> import urllib
>>> eu='http%3A%2F%2Fwww.baidu.com%2Fcache%2Fuser%2Fhtml%2Fv3Jump.html'
>>> du=urllib.unquote(eu)
>>> du
'http://www.baidu.com/cache/user/html/v3Jump.html'

45.python3 print函数 可以用end参数来定义结束符
print(' ', end='', file=sys.stdout)  end=''不做换行, file=sys.stdout输出到显示屏

46.split函数
(n, m) = i.split(':', 1) 后面max参数为1 表示分割字符的时候把字符串以第1个符号进行分割。

47.用WITH打开议文件不用考虑文件关闭
with open('man_data.txt', 'w') as man_data:
        print(man, file=man_data)

相当于man_data = open('man_data,txt', 'w')

48.pickle的使用
import pickle
data = open('a.txt', 'wb')
pickle.dump([1,2,3], data)
data.close()
indata = open('a.txt', 'rb')
alist=pickle.load(indata)
print(alist)

49.利用集合来去重
>>> a=[1, 2, 3, 4, 2, 1]
>>> b=list(set(a))
>>> b
[1, 2, 3, 4]

50.class Athlete:
     def __init__(self, value=0):
          self.thing = value
     def how_big(self):
          return(len(self.thing))

d = Athlete("Holy Grail")  -->  Athlete.__init__(d, "Holy Grail")
d.how_big() -->  Athlete.how_big(d)

51.列表推导包含append函数
>>> a = []
>>> b = [1, 2, 3]
>>> for i in b:
     x = i*20
     a.append(x)
>>> a
[20, 40, 60]

等同于

>>> b = [1, 2, 3]
>>> c = [i*20 for i in b]
>>> c
[20, 40, 60]

52.如何检测一个变量是否存在

问题 链接

我想检测一个变量是否存在,我现在是这么做的

try:
    myVar
except NameError:
    # Doint smth

存在其他不是使用exception的方式么?

回答

检测本地变量

if 'myVar' in locals():
    # myVar exists.

检测全局变量

if 'myVar' in globals():
    # myVar exists.

检测一个对象是否包含某个属性

if hasattr(obj, 'attr_name'):
    # obj.attr_name exists.

53.如何扁平一个二维数组

问题 链接

l = [[1,2,3],[4,5,6], [7], [8,9]]
变为[1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9]

列表解析

[item for sublist in l for item in sublist]

等同

for sublist in l:
    for item in sublist:
        x.append(item)

54.函数默认参数只解析一次

默认值在函数 定义 作用域被解析,如下所示

i = 5

def f(arg=i):
    print arg

i = 6f()

将打印出 5.
重要警告 默认值只解析一次。 这造成字典、列表或大部分类实例等可变对象的行为会与期待的不太一样。例如,下例的函数在每次调用时都造成参数的累加

def f(a, L=[]):
    L.append(a)
    return L

print f(1)print f(2)print f(3)

这将会打印

[1][1, 2][1, 2, 3]

如果你不想在随后的调用中共享默认值,可以像这样写函数

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

55.参数列表的分拆
当你要传递的参数已经是一个列表,但要调用的函数却接受分开一个个的参数值,你可以在调用函数时加一个 * 操作符来自动把参数列表拆开

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

以同样的方式,可以使用 ** 操作符分拆关键字参数为字典

>>> def parrot(voltage, state='a stiff', action='voom'):
...     print "-- This parrot wouldn't", action,
...     print "if you put", voltage, "volts through it.",
...     print "E's", state, "!"
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

56.一种无名函数的速写法
def make_incrementor(n):
    return lambda x: x+n
f=make_incrementor(n)
#f等价于
#def f(x):
#       return x+n

57.列表推导式可以嵌套。

考虑以下的 3x4 矩阵, 一个列表中包含三个长度为4的列表

>>> matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]
现在,如果你想交换行和列,可以用列表推导式

>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
像前面看到的,嵌套的列表推导式是对 for 后面的内容进行求值,所以上例就等价于

>>> transposed = []
>>> for i in range(4):
...     transposed.append([row[i] for row in matrix])
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
反过来说,如下也是一样的

>>> transposed = []
>>> for i in range(4):
...     # the following 3 lines implement the nested listcomp
...     transposed_row = []
...     for row in matrix:
...         transposed_row.append(row[i])
...     transposed.append(transposed_row)
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
在实际中,你应该更喜欢使用内置函数组成复杂流程语句。 对此种情况 zip() 函数将会做的更好

>>> zip(*matrix)
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

等同于
>>>zip(matrix[0], matrix[1], matrix[2])


58. 不包含abc的字符串
re.compile(r'^((?!abc)w)+$')

59.遇到特殊字符写入文件报错可以使用
#coding:gb18030
import sys 
reload(sys) 
sys.setdefaultencoding("gb18030")

60.集合求差
>>> a={1,2,3,4,5,6,7}
>>> b={2,4,6}
>>> a.difference(b)
set([1, 3, 5, 7])

③ 对两个集合的 Union[并集]操作也是对称的。
④ 对两个集合的 Intersection[交集]操作也是对称的。
⑤ 对两个集合的 Difference[求差]操作不是对称的。

61. pip用豆瓣数据源更新
pip install XXXX -i http://pypi.douban.com/simple 


62.替换列表中符合条件的字符(如果字符串第一个字符为数字的改成a开头)
ax = [i if i[0].isdigit() == False else 'a'+i for i in l]

63.在列表前插入值
>>> a = [1, 2, 3]
>>> a.insert(0,99)
>>> a
[99, 1, 2, 3]

64.冒泡算法
a = [1, 4, 51, 92, 11]

for x in range(len(a)):
    for y in range(len(a)-1):
        if a[y] > a[y+1]:
            a[y+1], a[y] = a[y], a[y+1]
print a
     
65.查看元素在列表中的位置
list1.index('a')

67.ascii解码成汉字
>>> print 'c4e3bac3'.decode('hex')
你好
>>> print 'c4e3'.decode('hex')





原文地址:https://www.cnblogs.com/highroom/p/8684c97093c09b6b7e5612d2d61d650b.html