gdrocket 发表于 2017-4-23 07:38:38

Python 简洁学习

  最近由于项目需要,在这个周末简单学习了下Python,听网上说google员工学习python通常几天搞定。
  如果你熟悉其他语言,的确可以这么说,边学边用才是最好的实践道理,否则学了些永远用不到的也是得不偿失啊!
  这里介绍2本书:
  <a byte of python> 
  英文阅读地址:http://www.ibiblio.org/swaroopch/byteofpython/read/
  中文翻译地址:http://blog.csdn.net/i_nbfa/article/details/5870676
  <dive into python>
  阅读地址:http://www.diveintopython.org/
  以下为简单总结:
Python 一切都是对象,包括数字
类型
空:None
数字类型:整数、浮点数、复数
单引号 = 双引号 != 三引号(可指定多行)
Format使用:        print(‘{0} is {1} years old’.format(name,age))         #格式控制
                            '{0:.3}'.format(1/3)                                                   #小数点后保留三位
                            '{0:_^11}'.format('hello')                                          #下划线填充字符到11位
                            '{name} wrote {book}'.format(name='Swaroop',book='A Byte of Python')
 
运算符
**
幂运算
3**4=81
/
除法
4/3=1.33333333,但是在python2.6 发现是1,不知道3.0如何
//
取整数
4//3=1
%
取模(求余数)
8%2=0,-25.5%2.25=1.5
not
布尔非
notTrue=False
and
布尔与
 
or
布尔或
 
 
控制符
if
 If a > b:
       print(‘a>b’)
 elif a < b:
       print(‘a<b’)
 else:
       print(‘a=b’)
 
while
 while running:
       print(‘running’)
 print(‘done’)
 
for
 for i in range(1,5):
       print(i)
>>1
>>2
>>3
>>4
 
 for i in range(1,5,2):     #步长为2
       print(i)
>>1
>>3
 
函数
def functionName(x,y):
       print(x)
       print(y)
 
deffuntionName(x, y=1):      #默认实参
       print(x)
       print(y)
 
内置属性
__name__
If __name__== ‘__main__’:
       print(‘自己独立运行’)
else:
       print(‘被其他程序导入、引用’)
 
内置函数
dir()
dir(moduleName)         列出该模块的所有属性
 
数据结构:      列表、元组、字典、集合
 
列表
myList=[‘as’,123,‘dfg’]         #定义
myList.append(‘ddd’)               #添加
for item inmyList:                    #遍历
       print(item)
 
myList.sort()         #排序
len(myList)            #计算长度
del myList         #删除
 
堆栈:            myList.pop()
 
元组
zoo = (‘aa’,‘bb’)         #小括号可以省略
len(zoo)=2                  #元组长度2
newzoo=’cc’,zoo
len(newzoo)=2               #长度还是2            ‘cc’,(‘aa’, ‘bb’)
newzoo=’bb’          #访问
 
字典
dic={‘key1’:’value1’,
‘key2’:’value2’,
‘key3’:’value3’
}
del dic[‘key1’]                         #删除
forkey,value in dic.items():           #遍历
       print(key,value)
dic[‘key4’]=’value4’             #添加
dic.has_key(‘keyName’)           #是否含有该key
 
集合
bri=set([‘aa’,’bb’])                      #定义
‘aa’inbri=True                               #是否含有该元素
bric=bri.copy()                                 #复制
bric.add(‘cc’)                                 #添加
bric.issuperset(bri)=True                #子集判断 /包含于判断
bri.remove(‘bb’)                              #删除元素
bric &bir={‘aa’}  #bri.intersection(bric)={‘aa’}        #求交集
 
引用
shopList=[‘a’,’b’,’c’]
myList=shopList                               #引用
delshopList                                          #删除
print(shopList)=print(myList)=[‘b’,’c’]         #结果一致,因为是引用
 
myList=shopList[:]                              #以全切片新建一个拷贝
delshopList                                          #删除
print(shopList)!= print(myList)           #不相等,因为指向不同的对象
 
字符串
name=’abcd’
name.startswith(‘ab’)
name.find(‘bc’)!= -1
delimiter=’_*_’
list=[‘1’,’2’,’3’]
print(delimiter.join(list))=1_*_2_*_3
 
reverse=name[::-1]=’dcba’#反转字符串, 列表也可以
 
类-OOP
##每个函数定义时,第一个形参必须为self
 
class Persion:
       num=0                        #类变量 每个对象共享
       def __init__(self, name):   #初始化函数
              self.name = name
       def sayHi(self):              #自定义函数
              print(‘my name is ’,self.name)
 
p = Person(‘lucy’)
p.sayHi()
>>myname is lucy
 
##python中所有类成员都为public
除了双下划线开头的:     __nameXXX,为private
惯例:单下划线开头的:  _nameXXX,约定为private,但其实是public
 
文件操作
f = open(‘open.txt’,’w’)        #写模式打开文件
f.write(‘aaaaa’)                       #写文件
f.close()                                  #关闭文件
 
f=open(‘open.txt’)                  #默认读模式
whlie True:
       line=f.readline()
       if len(line) == 0:               #长度为0代表EOF
              break
       print(line,end=’’)
f.close()
 
with open(‘open.txt’)as f:
       for line in f:
              print(line,end=’’)
 
lambda 表达式             #返回新的函数对象
defmake_repeater(n):
       return lambda s : s*n
 
twice =make_repeater(2)
print(twice(‘word’))
print(twice(5))
>>wordword
>>10
 
列表解析
list=
newlist=
print(newlist)
>> 6, 8
 
函数接收元组+列表
def function_name(arg1,*args):
       for i in args:
              print(i)
 
def function_name(arg1,**args):
       for key, value in args.items():
              print(key, value)
 
想进一步深入可以参考 <dive into python> 和 官方文档, 资料很全。
 
 
 
 
 
 
 
 
--
页: [1]
查看完整版本: Python 简洁学习