您的位置:首页 > 编程语言 > Python开发

可点进来看看的一些Python基础

2017-04-14 16:03 218 查看
1.

判断类型除了用 type(L) 

推荐使用 isinstance(L, list)

2.

将 x 十进制数转换为十六进制,八进制,二进制

hex(x) oct(x) bin(x)

表示为字符串

3.

x in y,x not in y 成员对象测试

x is y,x is not y 对象实体测试

1 < a < 3 可连续比较

4.

// 取整除 - 返回商的整数部分

9//2 输出结果 4 , 9.0//2.0 输出结果 4.0

5.

int(3.4), float(3) 强制类型转换

6.

Decimal 模块:小数模块

Decimal("0.01")

decimal.getcontext().prec = 4 设置全局精度为 4,小数点后 4 位

Fraction 模块:分数模块

Fraction(4, 6) 4/6

可接收字符串类型的参数 Fraction("0.25") 1/4

7.

set :无序,不重复元素集

s1.union(s2) 并集

s1.intersection(s2) 交集

s1.difference(s2) 差集

s1,stmmetric_difference(s2) 在 s1 或者 s2 中,但不会同时出现在二者中

s.add('x')  s.remove('X') 增加删除

s.update([x,x,x])  更新

x in s, x not in s 存在某值

{x**2 for x in [1,2,3,4]} {16,1,4,9} 集合解析,无序

{x for x in 'span'} {'a','p','s','n'} 集合解析,无序

set 是可变对象,即不存在 hash 值,不能作为字典的键值

8.

frozenset :没有 add,remove 等方法

s = set([1,1,1])

x = set()

x.add(s)  error:set 是不可哈希类型

x.add(frozenset(s)) 

9.

布尔类型 bool:

type(bool) 返回 <class 'bool'>

isinstance(False, int) bool类型属于整形,所以返回True

True == 1 True

True is l False

10.

变量名通过引用,指向对象

L = [1], M = [1] , L is M False

L = M = [1] , L is M True

L = L + [2,3]  # L = [1,2,3] M = [1]

L += [2,3] # L = [1,2,3] M = [1,2,3]

普通 + 对此对象进行修改成新的对象

增强赋值 += 会找到对象的起始点进行修改

11.

字符串操作:s1 + s2, s1 * 3, s[i], s[i:j], len(s) 

字符串格式化表达式:'xxx %s yyy' % 'kind'

字符串格式化方法: 'x {1} {0} b'.format('c', 'v')

字符串迭代:

>>> s = "zhaoyi"

>>> for x in s: print (x)

... 

z

h

a

o

y

i

字符串列表解析:

>>> print [y * 2 for y in s]

['zz', 'hh', 'aa', 'oo', 'yy', 'ii']

字符串输出:

>>> print ','.join(['a','b','c'])

a,b,c

12.

部分内置函数 str 功能:

首字母大写:capitalize()

每个单词首字母大写:title()

13.

""" 编写多行字符串,并自己引入\n

temp = """ fdsfdsfs
dsada
 dsadsfs """

temp 是 fdsfdsfs\n dsada \n dsadsfs

14.

>>> S = [1,2,3,4,5,6,7,8,9,10,11,22]

>>> S[1:10:2]

[2, 4, 6, 8, 10]

>>> S[:-1]

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

>>> S[1:]

[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 22]

>>> S[-1]

22

>>> S[0]

1

>>> 

15.

基于字典的格式化表达式

>>> print "%(n1)d---%(n2)s" % {"n1":11, "n2":"von"}

11---von

16.

a = [0,1,2,3,4,5,6,7]

del a[::2]

除去偶数项,a = [1,3,5,7]

17.

dict.update(dict_other) # 合并字典

dict.popitem() # 随机的一项键值对

字典键不一定非得是字符串,也可以为任何的不可变对象

字符串,整数,tuple都是不可变对象

18.

字典解析

>>> D = {k:8 for k in ['d','s']}

>>> D

{'s': 8, 'd': 8}

>>> z = {k:v for (k,v) in zip(['name', 'age'], ['tom', 12])}

>>> z

{'age': 12, 'name': 'tom'}

19.

元组和列表的唯一区别在于元组是不可变对象,列表是可变对象

不仅仅是长度不可变,元素也是不可变的

20.

元组的逗号和圆括号

>>> d = (12)

>>> d

12

>>> d = (12,)

>>> d

(12,)

21.

通常意义下的类型分类:

1.数字、序列、映射

2.可变类型和不可变类型

22.

常见赋值的形式

>>> sm = 'sm'

>>> sm

'sm'

>>> sm, sw = 'spam', 'swap'

>>> sm

'spam'

>>> sw

'swap'

>>> [sm, sw] = ['s', 'h']

>>> sm

's'

>>> sw

'h'

>>> a, b, c, d = 'abcd'

>>> a

'a'

>>> b

'b'

>>> c

'c'

>>> d

'd'

>>> sm = se = 'hh'

>>> sm

'hh'

>>> se

'hh'

Python3.x 有的序列解包形式

a, *b, c = 'sw'

23.

>>> 1 or 3 or 2

1

>>> 1 and 2 and 5

5

>>> 

and 或者 or 总是返回左边的对象或者右边的对象且具有短路求值的特性

24.

if/else 三元表达符

>>> x = 4

>>> a = 1 if x else 2

>>> a

1

>>> y = 0

>>> a = 1 if x else (2 if y else 3)

>>> a

1

>>> x = 0

>>> a = 1 if x else (2 if y else 3)

>>> a

3

也可用 and-or

>>> result = (a > 20 and "bigger than 20" or a > 10 and "bigger than 10")

>>> result

'bigger than 10'

25.

Python 的 while 语句或者 for 语句可以带else,当然也可以带 continue/break/pass

while a > 1:
lala

else:
hehe

for i in range(5):
lala

else:
hehe

else语句会在循环结束后执行

26.

>>> r = [a if a > 0 else 0 for a in [-1, 0, 1]]

>>> r

[0, 0, 1]

带判断条件的高级解析过程

>>> for a, b in zip(['A', 'A+'], ['B', 'B+']):

...  print (a + "vs" + b)

... 

AvsB

A+vsB+

>>> for index, data in enumerate(['a', 'b', 'c']):

...     print (index, data)

... 

(0, 'a')

(1, 'b')

(2, 'c')

enumerate 用处还是挺广泛的

27.

命名惯例

以单一下划线开头的变量名(_X)不会被from module import*等语句导入

前后有两个下划线的变量名(__X__)是系统定义的变量名,对解释器有特殊意义

以两个下划线开头但不以下划线结尾的变量名(__X)是类的本地(私有)变量

28.

手动迭代

>>> L = [1,2,3]

>>> i = iter(L)

>>> i.next()

1

>>> i.next()

2

>>> i.next()

3

>>> i.next()

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

StopIteration

29.

函数参数 * 和 ** 使用

>>> def f(a, *b, **c):

...     print (a,b,c)

... 

>>> f(1,2,3,x=4,y=5)

(1, (2, 3), {'y': 5, 'x': 4})

func(1, *(2, 3), **{'c':3, 'b':2})

等价于

func(1, 2, 3, b = 2, c = 3)

30.

了解 Lambda 的基本使用

>>> f1 = lambda x, y, z : x + y + z

>>> f1(1,2,3)

6

>>> f2 = lambda x = 1, y = 1 : x + y

>>> f2

<function <lambda> at 0x7fa2d68606e0>

>>> f2()

2

>>> list(map((lambda x: x+2), [1,2,3]))

[3, 4, 5]

>>> list(filter((lambda x: x>0), range(-4,5)))

[1, 2, 3, 4]

>>> reduce((lambda x, y: x + y), [1, 2, 3])

6

31.

生成器函数 yield

>>> def gen(N):

...     for i in range(N):

...             yield i ** 2

... 

>>> for i in gen(5):

...     print(i)

... 

0

1

4

9

16

>>> x = gen(2)

>>> next(x)

0

>>> next(x)

1

>>> next(x)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

StopIteration

如果说上面用的是 return,那么最终只会返回一个值,并不能达到展示过程的目的,而 yield 可以将状态挂起,恢复到那一时刻的状态

32.

生成器表达式 小括号进行列表解析

>>> g = (x ** 2 for x in range(3))

>>> next(g)

0

>>> next(g)

1

>>> next(g)

4

>>> next(g)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

StopIteration

生成器是单个迭代对象

>>> gen = (i for i in range(4))

>>> 2 in gen

True

>>> 3 in gen

True

>>> 1 in gen

False

生成器不保留迭代后的结果,检测2的时候,1已经跳过去不在了,同理2,3也不在了

33.

函数的默认值,我认为,可变的类型,参数在实例化是变化的,不可变的类型,在实例化是不可变的

>>> def foo(number=[]):

...     number.append(3)

...     print (number)

... 

>>> foo()

[3]

>>> foo()

[3, 3]

>>> foo()

[3, 3, 3]

改进

>>> def foo(number=None):

...     if number is None:

...             number = []

...     number.append(33)

...     print (number)

... 

>>> foo()

[33]

>>> foo()

[33]

>>> foo()

[33]

数字为参数,数字不可变

>>> def foo(count=1):

...     count += 1

...     print (count)

... 

>>> foo()

2

>>> foo()

2

>>> foo(4)

5

>>> foo(4)

5

>>> foo()

2

34.

Python中的多维数组

>>> lists = [0]*3

>>> lists

[0, 0, 0]

>>> lists = [[]] * 3

>>> lists[0].append(3)

>>> lists

[[3], [3], [3]]

>>> lists = [[] for i in range(3)]

>>> lists[0].append(3)

>>> lists[1].append(4)

>>> lists[2].append(5)

>>> lists

[[3], [4], [5]]

>>> lists = [[[] for j in range(4)] for i in range(3)]  # 3行4列

35.

import sys

sys.stdout # 是类文件对象,但是它们都只写,write()

sys.stdout.write("XXXX")

36.

包相对导入

from . import spam # 导入当前目录下的 spam 模块(错误:当前目录下的模块,直接导入即可)

from .spam import name # 导入当前目录下的 spam 模块的 name 属性(错误: 一定要加 . ,当前目录下的模块,不是直接导入)

from .. import spam # 导入当前目录的父目录下的 spam 

37.

Python 的类没有基于参数的函数重载

class temp:

  def test(self, string):
print (string)

  def test(self):
print ("hi")

后者 test 会覆盖前者

38.

class A(B):

  pass

a = A()

isinstance(a,B) # True ,A 是 B 的子类

39.

包装对象,委托 __getattr__ 钩子方法实现的,拦截对不存在属性的读取

class wrapper:

  def __init__(self, object):
self.wrapper = object
def __getattr(self, attrname):
print ('Trace:', attrname)
return getattr(self.wrapped, attrname)

getattr(X, N) 内置函数以变量名字字符串 N 从包装对象 X 中取出属性,类似于 X.__dict

x = wrapper([1,2,3])

x.append(4)

"Trace: append" [1,2,3,4]

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

x = wrapper({'a': 1, 'b': 2})

list(x.keys())

"Trace: keys" ['a', 'b']

40.

__attr 是类的伪私有属性

本面貌为: self._class.__attr = xxx 来改变

41.

动态语言灵活性

可给一个 class 的实例,继续添加属性和方法,使用 MethodType

c = Class()

c.new_method = MethodType(new_method, c) # 给实例加方法,类的其他实例不受影响

Class.new_method = MethodType(new_method, Student)
# 给类绑定一个方法,所有实例共有

42.

函数装饰器

@staticmethod

def smeth(x):

  print x

等价于

def smeth(x):

  print x

smeth = staticmethod(smeth)

一般都为内置函数吧

43.

类修饰器

def dec(XXX):
pass

@dec

class C:
pass

等价于

class C:
pass

C = dec(C)

44.

class sss:
__slots__('1', '2')# 可列表可元组

限制只有1,2两个属性

只对当前类起作用,子类不起作用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: