python開發學習一

來源:互聯網
上載者:User

標籤:byte   upd   pca   存在   分組   下載   布爾值   第一個字元   oba   

一.python的發展

python的創始人為吉多·范羅蘇姆(Guido van Rossum)。1989年的聖誕節期間,吉多·范羅蘇姆為了在阿姆斯特丹打發時間,決心開發一個新的指令碼解釋程式,作為ABC語言的一種繼承。 

python是一門動態解釋性的強型別定義語言。

因此在編程中,類型的轉換是需要特別注意的。而由於不會在初始設定變數的時候就確定其類型,而是由其賦予的值決定。因此要注意同名變數的情況以及變數定義的範圍,防止變數與自己想要的不一致。

當然,pyc的檔案存在,python在解譯器執行前會編譯的

二.python的安裝

最好是python3.x

windows下安裝:

1、下載安裝包

    https://www.python.org/downloads/

2、安裝

    預設安裝路徑:C:\python27

3、配置環境變數

    【右鍵電腦】--》【屬性】--》【進階系統設定】--》【進階】--》【環境變數】--》【在第二個內容框中找到 變數名為Path 的一行,雙擊】 --> 【Python安裝目錄追加到變值值中,用 ; 分割】

    如:原來的值;C:\python27,切記前面有分號

cmd--》python--》顯示資訊--》成功

linux,mac內建

三.基礎知識之變數

用來儲存資料

變數定義的規則:
      • 變數名只能是 字母、數字或底線的任意組合
      • 變數名的第一個字元不能是數字
      • 以下關鍵字不能聲明為變數名
        ‘and‘, ‘as‘, ‘assert‘, ‘break‘, ‘class‘, ‘continue‘, ‘def‘, ‘del‘, ‘elif‘, ‘else‘, ‘except‘, ‘exec‘, ‘finally‘,
      • ‘for‘, ‘from‘, ‘global‘, ‘if‘, ‘import‘, ‘in‘, ‘is‘, ‘lambda‘, ‘not‘, ‘or‘, ‘pass‘, ‘print‘, ‘raise‘, ‘return‘, ‘try‘, ‘while‘, ‘with‘, ‘yield‘

建議使用字母_字母的格式,最好有意義。

變數的資料類型

1.數字

int(整型)  在32位機器上,整數的位元為32位,取值範圍為-2**31~2**31-1,即-2147483648~2147483647
  在64位系統上,整數的位元為64位,取值範圍為-2**63~2**63-1,即-9223372036854775808~9223372036854775807long(長整型)
  跟C語言不同,Python的長整數沒有指定位寬,即:Python沒有限制長整數數值的大小,但實際上由於機器記憶體有限,我們使用的長整數數值不可能無限大。
  注意,自從Python2.2起,如果整數發生溢出,Python會自動將整數資料轉換為長整數,所以如今在長整數資料後面不加字母L也不會導致嚴重後果了。
float(浮點型)       先掃盲 http://www.cnblogs.com/alex3714/articles/5895848.html 
  浮點數用來處理實數,即帶有小數的數字。類似於C語言中的double類型,佔8個位元組(64位),其中52位表示底,11位表示指數,剩下的一位表示符號。
complex(複數)
  複數由實數部分和虛數部分組成,一般形式為x+yj,其中的x是複數的實數部分,y是複數的虛數部分,這裡的x和y都是實數。註:Python中存在小數字池:-5 ~ 257 2、布爾值  真或假  1 或 0 3、字串  "字串"(沒有字元與字串的區別,可用""或‘‘都行)  注意‘+’的使用,會開闢新的記憶體  "string is %s,%s"%(str1,str2)字串的格式化輸出字串是 %s;整數 %d;浮點數%f

在字元,中文,以及資料轉送等方面,字元編碼會影響。python3中會預設以unicode的格式。注意使用encode()與decode()方法進行編碼的轉換

4.列表(list)

[‘a‘,1,b] or list([1,2,3])

5.元組(tuple)

不可變的列表

6.字典(dict)

{‘name‘:‘aa‘,‘c‘:[1.2,3]} or dict({‘name‘:‘aa‘,‘c‘:[1.2,3]})

注釋 : #單行

    """多行 """或‘‘‘多行‘‘‘(注意,變數 = """文檔內容"""作為字串)

四.基本的運算

+,-,*,/,%,and,or,not,<>,!=,//,in,not in,。。。

if 判斷條件:

  注意縮排

  執行代碼

elif 判斷條件:

  xxxxx

else:

  xxxxx

while 條件:

  do something

for i in iter:

  looping...

注意迴圈的結束條件,break與continue的使用及作用範圍

 

五.列表的操作

定義:persons = [‘a‘,12]

根據下標擷取列表資料:persons[0],倒著取persons[-1]

切片:

  >>> names = ["Alex","Tenglan","Eric","Rain","Tom","Amy"]
  >>> names[1:4]  #取下標1至下標4之間的數字,包括1,不包括4
  [‘Tenglan‘, ‘Eric‘, ‘Rain‘]
  >>> names[1:-1] #取下標1至-1的值,不包括-1
  [‘Tenglan‘, ‘Eric‘, ‘Rain‘, ‘Tom‘]
  >>> names[0:3]
  [‘Alex‘, ‘Tenglan‘, ‘Eric‘]
  >>> names[:3] #如果是從頭開始取,0可以忽略,跟上句效果一樣
  [‘Alex‘, ‘Tenglan‘, ‘Eric‘]
  >>> names[3:] #如果想取最後一個,必須不能寫-1,只能這麼寫
  [‘Rain‘, ‘Tom‘, ‘Amy‘]
  >>> names[3:-1] #這樣-1就不會被包含了
  [‘Rain‘, ‘Tom‘]
  >>> names[0::2] #後面的2是代表,每隔一個元素,就取一個
  [‘Alex‘, ‘Eric‘, ‘Tom‘]
  >>> names[::2] #和上句效果一樣
  [‘Alex‘, ‘Eric‘, ‘Tom‘]

添加:persons.append(添加),添加到末尾

插入:persons.insert(位置,內容),指定位置

修改:persons[index] = 內容,直接修改

刪除:

  del persons刪除列表,

  del persons[index]刪除指定位置元素

  persons.remove(元素)刪除指定的值

  persons.pop()刪除末尾

拓展:

  >>> names
  [‘Alex‘, ‘Tenglan‘, ‘Rain‘, ‘Tom‘, ‘Amy‘]
  >>> b = [1,2,3]
  >>> names.extend(b)
  >>> names
  [‘Alex‘, ‘Tenglan‘, ‘Rain‘, ‘Tom‘, ‘Amy‘, 1, 2, 3]

淺拷貝:copy()

統計元素出現次數:list.count(元素)

其他:sort()排序,reverse()翻轉,index(元素)獲得第一元素出線的下標

元組的使用count,與index

六.字串(不可被修改)

name.capitalize()  首字母大寫
name.casefold()   大寫全部變小寫
name.center(50,"-")  輸出 ‘---------------------Alex Li----------------------‘
name.count(‘lex‘) 統計 lex出現次數
name.encode()  將字串編碼成bytes格式
name.endswith("Li")  判斷字串是否以 Li結尾
 "Alex\tLi".expandtabs(10) 輸出‘Alex      Li‘, 將\t轉換成多長的空格
 name.find(‘A‘)  尋找A,找到返回其索引, 找不到返回-1

format :
    >>> msg = "my name is {}, and age is {}"
    >>> msg.format("alex",22)
    ‘my name is alex, and age is 22‘
    >>> msg = "my name is {1}, and age is {0}"
    >>> msg.format("alex",22)
    ‘my name is 22, and age is alex‘
    >>> msg = "my name is {name}, and age is {age}"
    >>> msg.format(age=22,name="ale")
    ‘my name is ale, and age is 22‘
format_map
    >>> msg.format_map({‘name‘:‘alex‘,‘age‘:22})
    ‘my name is alex, and age is 22‘

msg.index(‘a‘)  返回a所在字串的索引
‘9aA‘.isalnum()   True

‘9‘.isdigit() 是否整數
name.isnumeric  
name.isprintable
name.isspace
name.istitle
name.isupper
 "|".join([‘alex‘,‘jack‘,‘rain‘])
‘alex|jack|rain‘

maketrans
    >>> intab = "aeiou"  #This is the string having actual characters.
    >>> outtab = "12345" #This is the string having corresponding mapping character
    >>> trantab = str.maketrans(intab, outtab)
    >>>
    >>> str = "this is string example....wow!!!"
    >>> str.translate(trantab)
    ‘th3s 3s str3ng 2x1mpl2....w4w!!!‘

 msg.partition(‘is‘)   輸出 (‘my name ‘, ‘is‘, ‘ {name}, and age is {age}‘)

 >>> "alex li, chinese name is lijie".replace("li","LI",1)
     ‘alex LI, chinese name is lijie‘

 msg.swapcase 大小寫互換
 >>> msg.zfill(40)
‘00000my name is {name}, and age is {age}‘

>>> n4.ljust(40,"-")
‘Hello 2orld-----------------------------‘
>>> n4.rjust(40,"-")
‘-----------------------------Hello 2orld‘

>>> b="ddefdsdff_哈哈"
>>> b.isidentifier() #檢測一段字串可否被當作標誌符,即是否符合變數命名規則
True

七.字典

key-value,無序,key值唯一

 增加/修改:dic[key] = value

刪除:dict.remove(key),del dict[key],隨機刪除dict.removeitem()

尋找:key in dict 尋找key是否在字典中

    dict.get(key)獲得value,如果沒有key,返回None

    dict[key]如果key不存在,會拋出異常

其他:

#values
>>> info.values()
dict_values([‘LongZe Luola‘, ‘XiaoZe Maliya‘])

#keys
>>> info.keys()
dict_keys([‘stu1102‘, ‘stu1103‘])

#setdefault
>>> info.setdefault("stu1106","Alex")
‘Alex‘
>>> info
{‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1106‘: ‘Alex‘}
>>> info.setdefault("stu1102","龍澤蘿拉")
‘LongZe Luola‘
>>> info
{‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1106‘: ‘Alex‘}

#update
>>> info
{‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1106‘: ‘Alex‘}
>>> b = {1:2,3:4, "stu1102":"龍澤蘿拉"}
>>> info.update(b)
>>> info
{‘stu1102‘: ‘龍澤蘿拉‘, 1: 2, 3: 4, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1106‘: ‘Alex‘}

#items
info.items()
dict_items([(‘stu1102‘, ‘龍澤蘿拉‘), (1, 2), (3, 4), (‘stu1103‘, ‘XiaoZe Maliya‘), (‘stu1106‘, ‘Alex‘)])


#通過一個列表產生預設dict,有個沒辦法解釋的坑,少用吧這個
>>> dict.fromkeys([1,2,3],‘testd‘)
{1: ‘testd‘, 2: ‘testd‘, 3: ‘testd‘}

字典的迴圈:

#方法1
for key in info:
    print(key,info[key])

#方法2
for k,v in info.items(): #會先把dict轉成list,資料裡大時莫用
    print(k,v)

 

八.集合

集合是一個無序的,不重複的資料群組合,它的主要作用如下:

  • 去重,把一個列表變成集合,就自動去重了
  • 關係測試,測試兩組資料之前的交集、差集、並集等關係

s = set([3,5,9,10])      #建立一個數值集合  
 
t = set("Hello")         #建立一個唯一字元的集合  

a = t | s          # t 和 s的並集  
 
b = t & s          # t 和 s的交集  
 
c = t – s          # 求差集(項在t中,但不在s中)  
 
d = t ^ s          # 對稱差集(項在t或s中,但不會同時出現在二者中)  
 
   
 
基本操作:  
 
t.add(‘x‘)            # 添加一項  
 
使用remove()可以刪除一項:  
 t.remove(‘H‘) 
 

len(s) 
set 的長度  
 
x in s  
測試 x 是否是 s 的成員  
 
x not in s  
測試 x 是否不是 s 的成員  
 
s.issubset(t)  
s <= t  
測試是否 s 中的每一個元素都在 t 中  
 
s.issuperset(t)  
s >= t  
測試是否 t 中的每一個元素都在 s 中  
 
s.union(t)  
s | t  
返回一個新的 set 包含 s 和 t 中的每一個元素  
 
s.intersection(t)  
s & t  
返回一個新的 set 包含 s 和 t 中的公用元素  
 
s.difference(t)  
s - t  
返回一個新的 set 包含 s 中有但是 t 中沒有的元素  
 
s.symmetric_difference(t)  
s ^ t  
返回一個新的 set 包含 s 和 t 中不重複的元素  
 
s.copy()  
返回 set “s”的一個淺複製

 ----大量參考了

    http://www.cnblogs.com/alex3714/articles/5465198.html

    http://www.cnblogs.com/alex3714/articles/5717620.html   

 

python開發學習一

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.