【大數據技術能力提高_1】python基礎

 

 

 

 

程序輸入與輸出

 

打印字符串

In [1]:
myString = "hello word"
print myString
 
hello word
 

格式化字符串

In [7]:
print "%s is number %d!"%("python",1)
print "{} is number {}!".format("python",2) #python官方推薦
 
python is number 1!
python is number 2!
 

重定向

In [12]:
import sys
print >> sys.stderr,"write to standard error"
logfile = open('./deleteme.txt','wb')
print >> logfile, "write to deleteme.txt"
logfile.close()
 
write to standard error
 

交互式輸入

In [15]:
username = raw_input('enter your name:')
 
enter your name:11
In [16]:
username #輸出值都是字符串
Out[16]:
'11'
 

print的小tip

 

帶都好的print語句輸出的元素之間會自動添加一個空格

In [17]:
print 'hello', 'world'
 
hello world
 

print會在最後添加一個換行符

In [19]:
for c in 'hello':
    print c
 
h
e
l
l
o
 

print最後增長一個都好,會抑制換行符

In [20]:
for c in 'hello':
    print c,
 
h e l l o
 

註釋

 

普通註釋

In [21]:
# one comment
 

文檔註釋

In [22]:
def func():
    "this is doc string"
 

操做符

In [24]:
print -1*3+2**3+1/3
print 2**3
 
5
8
 

變量和賦值

變量由字母或下劃線開頭,其餘字符能夠是數字、字母和下劃線

不惜要預先聲明

支持增量賦值,但不支持自減自增(i++)

 

數字

python 中int會被自動轉換成long,從python2.3開始

In [26]:
print long(10),float(10),bool(10),complex(10)
 
 10 10.0 True (10+0j)
 

字符串

 

單引號、雙引號、三引號都可

三引號能夠用來包含特殊字符,不須要轉義(如換行)

In [29]:
print 'a"b"'
 
a"b"
In [30]:
print "a'b'"
 
a'b'
In [31]:
print '''a
b
c'''
 
a
b
c
 

索引與切片

In [28]:
astring = 'python'
print astring[0]
print astring[1:2]
print astring[:2]
print astring[2:]
print astring[-1]
print astring + 'is cool'
print astring * 2
 
p
y
py
thon
n
pythonis cool
pythonpython
 

字符串編碼

避免亂碼

輸入時解碼

輸出時編碼

unicode.encode() -> bytes; bytes.decode() -> unicodejavascript

 

列表與元組

二者索引與切片相似於字符串

列表可修改

元組不可修改

In [33]:
alist = ['jack',3,1.0]
alist
Out[33]:
['jack', 3, 1.0]
In [34]:
atuple = ('rose',1,3.0)
atuple
Out[34]:
('rose', 1, 3.0)
 

字典

工做原理相似哈希表,由鍵-值(key-value)對組成

In [37]:
adict = {'hose':'baidu','port':80}
print adict
print adict.keys()
for key,value in adict.items():
    print key,value
 
{'hose': 'baidu', 'port': 80}
['hose', 'port']
hose baidu
port 80
 

集合

無重複元素

盡心交、並、差運算

In [38]:
print alist
 
['jack', 3, 1.0]
In [40]:
aset = set(alist)
print aset
bset = set([3.5,'jack'])
print aset.intersection(bset) #交集
print aset.difference(bset) #並集
 
set([1.0, 3, 'jack'])
set(['jack'])
set([1.0, 3])
 

if語句

if,elif,slse

沒有switch/case語句

 

for循環

用for遍歷字符串或列表或元組

 

enumerate返回元素自己和id

 

for else

In [42]:
for i in range(0,1):
    if i==2:
        print 1
else:
    print 0
 
0
 

列表解析(列表推導)

In [43]:
cube = [x**3 for x in range(4)]
cube
Out[43]:
[0, 1, 8, 27]
In [44]:
cube = [x**3 for x in range(4) if not x%2]
cube
Out[44]:
[0, 8]
 

字典也能夠

In [48]:
adict = {'one':1,'two':2}
cube = {key+'_cube':value**3 for key,value in adict.items()}
cube
Out[48]:
{'one_cube': 1, 'two_cube': 8}
 

文件

open,file

訪問模式:‘r’ 讀,‘w’ 寫,‘a’ 添加,‘+’,‘b’ 二進制訪問

更好的實踐:with open(filename,access_mode)as fp:

 

錯誤與異常

try except (與java相似)

最好用finally

 

函數

In [49]:
def add(x,y=1):
    return x+y
In [50]:
add(3)
Out[50]:
4
 

定義類

In [70]:
class FooClase(object):
    version = 0.1
    
    def __init__(self, name='no name'):
        self.name = name
        print 'create a class instance for'
    
    def showname(self):
        print 'your name is', self.name
        print 'myname is', self.__class__.__name__
    
    def showver(self):
        print self.version
    
    def addMe(self, x):
        return x + x
 
In [72]:
folo1 = FooClase()
folo1.showname()
 
create a class instance for
your name is no name
myname is FooClase
In [74]:
folo1.showver()
 
0.1
In [75]:
print folo1.addMe(5)
 
10
 

模塊

導入模塊 import

訪問模塊的函數或者變量(模塊名.函數)

 

實用函數


help(obj) 在線幫助, obj但是任何類型

  callable(obj) 查看一個obj是否是能夠像函數同樣調用css

  repr(obj) 獲得obj的表示字符串,能夠利用這個字符串eval重建該對象的一個拷貝html

  eval_r(str) 表示合法的python表達式,返回這個表達式html5

  dir(obj) 查看obj的name space中可見的namejava

  hasattr(obj,name) 查看一個obj的name space中是否有namenode

  getattr(obj,name) 獲得一個obj的name space中的一個namepython

  setattr(obj,name,value) 爲一個obj的name space中的一個name指向vale這個objectjquery

  delattr(obj,name) 從obj的name space中刪除一個namelinux

  vars(obj) 返回一個object的name space。用dictionary表示android

  locals() 返回一個局部name space,用dictionary表示

  globals() 返回一個全局name space,用dictionary表示

  type(obj) 查看一個obj的類型

  isinstance(obj,cls) 查看obj是否是cls的instance

  issubclass(subcls,supcls) 查看subcls是否是supcls的子類

相關文章
相關標籤/搜索