<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          【Python基礎(chǔ)】適合小白的Python 簡易入門指南(附代碼)

          共 4712字,需瀏覽 10分鐘

           ·

          2020-12-22 17:25

          0.導(dǎo)語

          Python是一種跨平臺的計算機(jī)程序設(shè)計語言。是一種面向?qū)ο蟮膭討B(tài)類型語言,最初被設(shè)計用于編寫自動化腳本(shell),隨著版本的不斷更新和語言新功能的添加,越來越多被用于獨(dú)立的、大型項(xiàng)目的開發(fā)。

          在此之前,我已經(jīng)寫了以下幾篇AI基礎(chǔ)的快速入門,本篇文章講解python語言的基礎(chǔ)部分,也是后續(xù)內(nèi)容的基礎(chǔ)。

          本文代碼可以在github下載:

          https://github.com/fengdu78/Data-Science-Notes/tree/master/1.python-basic

          文件名:Python_Basic.ipynb

          1 Python數(shù)據(jù)類型

          1.1 字符串

          在Python中用引號引起來的字符集稱之為字符串,比如:'hello'、"my Python"、"2+3"等都是字符串 Python中字符串中使用的引號可以是單引號、雙引號跟三引號

          print ('hello world!')
          hello world!
          c = 'It is a "dog"!'
          print (c)
          It is a "dog"!
          c1= "It's a dog!"
          print (c1)
          It's a dog!
          c2 = """hello
          world
          !"""

          print (c2)
          hello
          world
          !
          • 轉(zhuǎn)義字符''

          轉(zhuǎn)義字符\可以轉(zhuǎn)義很多字符,比如\n表示換行,\t表示制表符,字符\本身也要轉(zhuǎn)義,所以\ \表示的字符就是\

          print ('It\'s a dog!')
          print ("hello world!\nhello Python!")
          print ('\\\t\\')
          It's a dog!
          hello world!
          hello Python!
          \ \

          原樣輸出引號內(nèi)字符串可以使用在引號前加r

          print (r'\\\t\\')
          \\\t\\
          • 子字符串及運(yùn)算
          s = 'Python'
          print( 'Py' in s)
          print( 'py' in s)
          True
          False

          取子字符串有兩種方法,使用[]索引或者切片運(yùn)算法[:],這兩個方法使用面非常廣

          print (s[2])
          t
          print (s[1:4])
          yth
          • 字符串連接與格式化輸出
          word1 = '"hello"'
          word2 = '"world"'
          sentence = word1.strip('"') + ' ' + word2.strip('"') + '!'

          print( 'The first word is %s, and the second word is %s' %(word1, word2))
          print (sentence)
          The first word is "hello", and the second word is "world"
          hello world!

          1.2 整數(shù)與浮點(diǎn)數(shù)

          整數(shù)

          Python可以處理任意大小的整數(shù),當(dāng)然包括負(fù)整數(shù),在程序中的表示方法和數(shù)學(xué)上的寫法一模一樣

          i = 7
          print (i)
          7
          7 + 3
          10
          7 - 3
          4
          7 * 3
          21
          7 ** 3
          343
          7 / 3#Python3之后,整數(shù)除法和浮點(diǎn)數(shù)除法已經(jīng)沒有差異
          2.3333333333333335
          7 % 3
          1
          7//3
          2
          浮點(diǎn)數(shù)
          7.0 / 3
          2.3333333333333335
          3.14 * 10 ** 2
          314.0

          其它表示方法

          0b1111
          15
          0xff
          255
          1.2e-5
          1.2e-05

          更多運(yùn)算

          import math

          print (math.log(math.e)) # 更多運(yùn)算可查閱文檔
          1.0

          1.3 布爾值

          True
          True
          False
          False
          True and False
          False
          True or False
          True
          not True
          False
          True + False
          1
          18 >= 6 * 3 or 'py' in 'Python'
          True
          18 >= 6 * 3 and 'py' in 'Python'
          False
          18 >= 6 * 3 and 'Py' in 'Python'
          True

          1.4 日期時間

          import time

          now = time.strptime('2016-07-20', '%Y-%m-%d')
          print (now)
          time.struct_time(tm_year=2016, tm_mon=7, tm_mday=20, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=202, tm_isdst=-1)
          time.strftime('%Y-%m-%d', now)
          '2016-07-20'
          import datetime

          someDay = datetime.date(1999,2,10)
          anotherDay = datetime.date(1999,2,15)
          deltaDay = anotherDay - someDay
          deltaDay.days
          5

          還有其他一些datetime格式

          • 查看變量類型
          type(None)
          NoneType
          type(1.0)
          float
          type(True)
          bool
          s="NoneType"
          type(s)
          str
          • 類型轉(zhuǎn)換
          str(10086)
          '10086'
          ?float()
          float(10086)
          10086.0
          int('10086')
          10086
          complex(10086)
          (10086+0j)

          2 Python數(shù)據(jù)結(jié)構(gòu)

          列表(list)、元組(tuple)、集合(set)、字典(dict)

          2.1 列表(list)

          用來存儲一連串元素的容器,列表用[]來表示,其中元素的類型可不相同。

          mylist= [0, 1, 2, 3, 4, 5]
          print (mylist)
          [0, 1, 2, 3, 4, 5]

          列表索引和切片

          # 索引從0開始,含左不含右
          print ('[4]=', mylist[4])
          print ('[-4]=', mylist[-4])
          print ('[0:4]=', mylist[0:4])
          print ('[:4]=', mylist[:4])#dddd
          print( '[4:]=', mylist[4:])
          print ('[0:4:2]=', mylist[0:4:2])
          print ('[-5:-1:]=', mylist[-5:-1:])
          print ('[-2::-1]=', mylist[-2::-1])
          [4]= 4
          [-4]= 2
          [0:4]= [0, 1, 2, 3]
          [:4]= [0, 1, 2, 3]
          [4:]= [4, 5]
          [0:4:2]= [0, 2]
          [-5:-1:]= [1, 2, 3, 4]
          [-2::-1]= [4, 3, 2, 1, 0]

          修改列表

          mylist[3] = "小月"
          print (mylist[3])

          mylist[5]="小楠"
          print (mylist[5])

          mylist[5]=19978
          print (mylist[5])

          小月
          小楠
          19978
          print (mylist)
          [0, 1, 2, '小月', 4, 19978]

          插入元素

          mylist.append('han') # 添加到尾部
          mylist.extend(['long', 'wan'])
          print (mylist)
          [0, 1, 2, '小月', 4, 19978, 'han', 'long', 'wan']
          scores = [90, 80, 75, 66]
          mylist.insert(1, scores) # 添加到指定位置
          mylist
          [0, [90, 80, 75, 66], 1, 2, '小月', 4, 19978, 'han', 'long', 'wan']
          a=[]

          刪除元素

          print (mylist.pop(1)) # 該函數(shù)返回被彈出的元素,不傳入?yún)?shù)則刪除最后一個元素
          print (mylist)
          [90, 80, 75, 66]
          [0, 1, 2, '小月', 4, 19978, 'han', 'long', 'wan']

          判斷元素是否在列表中等

          print( 'wan' in mylist)
          print ('han' not in mylist)
          True
          False
          mylist.count('wan')
          1
          mylist.index('wan')
          8

          range函數(shù)生成整數(shù)列表

          print (range(10))
          print (range(-5, 5))
          print (range(-10, 10, 2))
          print (range(16, 10, -1))
          range(0, 10)
          range(-5, 5)
          range(-10, 10, 2)
          range(16, 10, -1)

          2.2 元組(tuple)

          元組類似列表,元組里面的元素也是進(jìn)行索引計算。列表里面的元素的值可以修改,而元組里面的元素的值不能修改,只能讀取。元組的符號是()。

          studentsTuple = ("ming", "jun", "qiang", "wu", scores)
          studentsTuple
          ('ming', 'jun', 'qiang', 'wu', [90, 80, 75, 66])
          try:
          studentsTuple[1] = 'fu'
          except TypeError:
          print ('TypeError')
          TypeError
          scores[1]= 100
          studentsTuple
          ('ming', 'jun', 'qiang', 'wu', [90, 100, 75, 66])
          'ming' in studentsTuple
          True
          studentsTuple[0:4]
          ('ming', 'jun', 'qiang', 'wu')
          studentsTuple.count('ming')
          1
          studentsTuple.index('jun')
          1
          len(studentsTuple)
          5

          2.3 集合(set)

          Python中集合主要有兩個功能,一個功能是進(jìn)行集合操作,另一個功能是消除重復(fù)元素。集合的格式是:set(),其中()內(nèi)可以是列表、字典或字符串,因?yàn)樽址且粤斜淼男问酱鎯Φ?/p>

          studentsSet = set(mylist)
          print (studentsSet)
          {0, 1, 2, 'han', 4, '小月', 19978, 'wan', 'long'}
          studentsSet.add('xu')
          print (studentsSet)
          {0, 1, 2, 'han', 4, '小月', 19978, 'wan', 'long', 'xu'}
          studentsSet.remove('xu')
          print (studentsSet)
          {0, 1, 2, 'han', 4, '小月', 19978, 'wan', 'long'}
          mylist.sort()#會出錯
          ---------------------------------------------------------------------------

          TypeError Traceback (most recent call last)

          in ()
          ----> 1 mylist.sort()


          TypeError: '<' not supported between instances of 'str' and 'int'
          a = set("abcnmaaaaggsng")
          print ('a=', a)
          a= {'b', 'a', 'm', 'c', 'g', 's', 'n'}
          b = set("cdfm")
          print ('b=', b)
          b= {'m', 'd', 'c', 'f'}
          #交集
          x = a & b
          print( 'x=', x)
          x= {'m', 'c'}
          #并集
          y = a | b
          print ('y=', y)
          #差集
          z = a - b
          print( 'z=', z)
          #去除重復(fù)元素
          new = set(a)
          print( z)
          y= {'b', 'a', 'f', 'd', 'm', 'c', 'g', 's', 'n'}
          z= {'b', 'a', 'g', 's', 'n'}
          {'b', 'a', 'g', 's', 'n'}

          2.4字典(dict)

          Python中的字典dict也叫做關(guān)聯(lián)數(shù)組,用大括號{}括起來,在其他語言中也稱為map,使用鍵-值(key-value)存儲,具有極快的查找速度,其中key不能重復(fù)。

          k = {"name":"weiwei", "home":"guilin"}
          print (k["home"])
          guilin
          print( k.keys())
          print( k.values())
          dict_keys(['name', 'home'])
          dict_values(['weiwei', 'guilin'])

          添加、修改字典里面的項(xiàng)目

          k["like"] = "music"
          k['name'] = 'guangzhou'
          print (k)
          {'name': 'guangzhou', 'home': 'guilin', 'like': 'music'}
          k.get('edu', -1) # 通過dict提供的get方法,如果key不存在,可以返回None,或者自己指定的value
          -1

          刪除key-value元素

          k.pop('like')
          print (k)
          {'name': 'guangzhou', 'home': 'guilin'}

          2.5 列表、元組、集合、字典的互相轉(zhuǎn)換

          type(mylist)
          list
          tuple(mylist)
          (0, 1, 2, '小月', 4, 19978, 'han', 'long', 'wan')
          list(k)
          ['name', 'home']
          zl = zip(('A', 'B', 'C'), [1, 2, 3, 4]) # zip可以將列表、元組、集合、字典‘縫合’起來
          print (zl)
          print (dict(zl))

          {'A': 1, 'B': 2, 'C': 3}

          3 Python控制流

          在Python中通常的情況下程序的執(zhí)行是從上往下執(zhí)行的,而某些時候我們?yōu)榱烁淖兂绦虻膱?zhí)行順序,使用控制流語句控制程序執(zhí)行方式。Python中有三種控制流類型:順序結(jié)構(gòu)、分支結(jié)構(gòu)、循環(huán)結(jié)構(gòu)。

          另外,Python可以使用分號";"分隔語句,但一般是使用換行來分隔;語句塊不用大括號"{}",而使用縮進(jìn)(可以使用四個空格)來表示

          3.1 順序結(jié)構(gòu)

          s = '7'
          num = int(s) # 一般不使用這種分隔方式
          num -= 1 # num = num - 1
          num *= 6 # num = num * 6
          print (num)
          36

          3.2 分支結(jié)構(gòu):Python中if語句是用來判斷選擇執(zhí)行哪個語句塊的

          if :

             執(zhí)行語句塊

          elif

             執(zhí)行語句塊

          else:? ? ? ?# 都不滿足

             執(zhí)行語句塊

          #elif子句可以有多條,elif和else部分可省略

          salary = 1000
          if salary > 10000:
          print ("Wow!!!!!!!")
          elif salary > 5000:
          print ("That's OK.")
          elif salary > 3000:
          print ("5555555555")
          else:
          print ("..........")
          ..........

          3.3 循環(huán)結(jié)構(gòu)

          while 循環(huán)

          while :

             循環(huán)執(zhí)行語句塊

          else:? ? ? ? ?# 不滿足條件

            執(zhí)行語句塊

          #else部分可以省略

          a = 1
          while a < 10:
          if a <= 5:
          print (a)
          else:
          print ("Hello")
          a = a + 1
          else:
          print ("Done")
          1
          2
          3
          4
          5
          Hello
          Hello
          Hello
          Hello
          Done
          • for 循環(huán) for (條件變量) in (集合):

            執(zhí)行語句塊

          “集合”并不單指set,而是“形似”集合的列表、元組、字典、數(shù)組都可以進(jìn)行循環(huán)

          條件變量可以有多個

          heights = {'Yao':226, 'Sharq':216, 'AI':183}
          for i in heights:
          print (i, heights[i])
          Yao 226
          Sharq 216
          AI 183
          for key, value in heights.items():
          print(key, value)
          Yao 226
          Sharq 216
          AI 183
          total = 0
          for i in range(1, 101):
          total += i#total=total+i
          print (total)
          5050

          3.4 break、continue和pass

          break:跳出循環(huán)

          continue:跳出當(dāng)前循環(huán),繼續(xù)下一次循環(huán)

          pass:占位符,什么也不做

          for i in range(1, 5):
          if i == 3:
          break
          print (i)
          1
          2
          for i in range(1, 5):
          if i == 3:
          continue
          print (i)
          1
          2
          4
          for i in range(1, 5):
          if i == 3:
          pass
          print (i)
          1
          2
          3
          4

          3.5 列表生成式

          三種形式

          • [<表達(dá)式> for (條件變量) in (集合)]
          • [<表達(dá)式> for (條件變量) in (集合) if <'True or False'表達(dá)式>]
          • [<表達(dá)式> if <'True or False'表達(dá)式> else <表達(dá)式> ?for (條件變量) in (集合) ]
          fruits = ['"Apple', 'Watermelon', '"Banana"']
          [x.strip('"') for x in fruits]
          ['Apple', 'Watermelon', 'Banana']
          # 另一種寫法
          test_list=[]
          for x in fruits:
          x=x.strip('"')
          test_list.append(x)
          test_list
          ['Apple', 'Watermelon', 'Banana']
          [x ** 2 for x in range(21) if x%2]
          [1, 9, 25, 49, 81, 121, 169, 225, 289, 361]
          # 另一種寫法
          test_list=[]
          for x in range(21):
          if x%2:
          x=x**2
          test_list.append(x)
          test_list
          [1, 9, 25, 49, 81, 121, 169, 225, 289, 361]
          [m + n for m in 'ABC' for n in 'XYZ']
          ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
          # 另一種寫法
          test_list=[]
          for m in 'ABC':
          for n in 'XYZ':
          x=m+n
          test_list.append(x)
          test_list
          ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
          d = {'x': 'A', 'y': 'B', 'z': 'C' }
          [k + '=' + v for k, v in d.items()]
          ['x=A', 'y=B', 'z=C']
          # 另一種寫法
          test_list=[]
          for k, v in d.items():
          x=k + '=' + v
          test_list.append(x)
          test_list
          ['x=A', 'y=B', 'z=C']

          4 Python函數(shù)

          函數(shù)是用來封裝特定功能的實(shí)體,可對不同類型和結(jié)構(gòu)的數(shù)據(jù)進(jìn)行操作,達(dá)到預(yù)定目標(biāo)。

          4.1 調(diào)用函數(shù)

          • Python內(nèi)置了很多有用的函數(shù),我們可以直接調(diào)用,進(jìn)行數(shù)據(jù)分析時多數(shù)情況下是通過調(diào)用定義好的函數(shù)來操作數(shù)據(jù)的
          str1 = "as"
          int1 = -9
          print (len(str1))
          print (abs(int1))
          2
          9
          fruits = ['Apple', 'Banana', 'Melon']
          fruits.append('Grape')
          print (fruits)
          ['Apple', 'Banana', 'Melon', 'Grape']

          4.2 定義函數(shù)

          當(dāng)系統(tǒng)自帶函數(shù)不足以完成指定的功能時,需要用戶自定義函數(shù)來完成。def 函數(shù)名():函數(shù)內(nèi)容 函數(shù)內(nèi)容

          def my_abs(x):
          if x >= 0:
          return x
          else:
          return -x

          my_abs(-9)
          9

          可以沒有return

          def filter_fruit(someList, d):
          for i in someList:
          if i == d:
          someList.remove(i)
          else:
          pass

          print (filter_fruit(fruits, 'Melon'))
          print (fruits)
          None
          ['Apple', 'Banana', 'Grape']

          多個返回值的情況

          def test(i, j):
          k = i * j
          return i, j, k

          a , b , c = test(4, 5)
          print (a, b , c)
          type(test(4, 5))
          4 5 20
          tuple

          4.3 高階函數(shù)

          • 把另一個函數(shù)作為參數(shù)傳入一個函數(shù),這樣的函數(shù)稱為高階函數(shù)

          函數(shù)本身也可以賦值給變量,函數(shù)與其它對象具有同等地位

          myFunction = abs
          myFunction(-9)
          9
          • 參數(shù)傳入函數(shù)
          def add(x, y, f):
          return f(x) + f(y)

          add(7, -5, myFunction)
          12
          • 常用高階函數(shù)

          map/reduce: map將傳入的函數(shù)依次作用到序列的每個元素,并把結(jié)果作為新的list返回;reduce把一個函數(shù)作用在一個序列[x1, x2, x3...]上,這個函數(shù)必須接收兩個參數(shù),reduce把結(jié)果繼續(xù)和序列的下一個元素做累積計算

          myList = [-1, 2, -3, 4, -5, 6, 7]
          map(abs, myList)

          from functools import reduce
          def powerAdd(a, b):
          return pow(a, 2) + pow(b, 2)

          reduce(powerAdd, myList) # 是否是計算平方和?
          3560020598205630145296938

          filter:filter()把傳入的函數(shù)依次作用于每個元素,然后根據(jù)返回值是True還是False決定保留還是丟棄該元素

          def is_odd(x):
          return x % 3 # 0被判斷為False,其它被判斷為True

          filter(is_odd, myList)

          sorted: 實(shí)現(xiàn)對序列排序,默認(rèn)情況下對于兩個元素x和y,如果認(rèn)為x < y,則返回-1,如果認(rèn)為x == y,則返回0,如果認(rèn)為x > y,則返回1

          默認(rèn)排序:數(shù)字大小或字母序(針對字符串)

          sorted(myList)
          [-5, -3, -1, 2, 4, 6, 7]

          *練習(xí):自定義一個排序規(guī)則函數(shù),可將列表中字符串忽略大小寫地,按字母序排列,列表為['Apple', 'orange', 'Peach', 'banana']。提示:字母轉(zhuǎn)換為大寫的方法為some_str.upper(),轉(zhuǎn)換為小寫使用some_str.lower()

          • 返回函數(shù): 高階函數(shù)除了可以接受函數(shù)作為參數(shù)外,還可以把函數(shù)作為結(jié)果值返回
          def powAdd(x, y):
          def power(n):
          return pow(x, n) + pow(y, n)
          return power

          myF = powAdd(3, 4)
          myF
          .power>
          myF(2)
          25
          • 匿名函數(shù):高階函數(shù)傳入函數(shù)時,不需要顯式地定義函數(shù),直接傳入匿名函數(shù)更方便
          f = lambda x: x * x
          f(4)
          16

          等同于:

          def f(x):
          return x * x
          map(lambda x: x * x, myList)

          匿名函數(shù)可以傳入多個參數(shù)

          reduce(lambda x, y: x + y, map(lambda x: x * x, myList))
          140

          返回函數(shù)可以是匿名函數(shù)

          def powAdd1(x, y):
          return lambda n: pow(x, n) + pow(y, n)

          lamb = powAdd1(3, 4)
          lamb(2)
          25

          其它

          • 標(biāo)識符第一個字符只能是字母或下劃線,第一個字符不能出現(xiàn)數(shù)字或其他字符;標(biāo)識符除第一個字符外,其他部分可以是字母或者下劃線或者數(shù)字,標(biāo)識符大小寫敏感,比如name跟Name是不同的標(biāo)識符。
          • Python規(guī)范:
          • 類標(biāo)識符每個字符第一個字母大寫;
          • 對象\變量標(biāo)識符的第一個字母小寫,其余首字母大寫,或使用下劃線'_' 連接;
          • 函數(shù)命名同普通對象。
          • 關(guān)鍵字

          關(guān)鍵字是指系統(tǒng)中自帶的具備特定含義的標(biāo)識符

          # 查看一下關(guān)鍵字有哪些,避免關(guān)鍵字做自定義標(biāo)識符
          import keyword
          print (keyword.kwlist)
          ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
          • 注釋

          Python中的注釋一般用#進(jìn)行注釋

          • 幫助

          Python中的注釋一般用?查看幫助

          往期精彩回顧





          獲取本站知識星球優(yōu)惠券,復(fù)制鏈接直接打開:

          https://t.zsxq.com/qFiUFMV

          本站qq群704220115。

          加入微信群請掃碼:

          瀏覽 45
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  精品日韩在线 | 日本三级精品视频 | 国产刺激高潮 | 青青操影院| 8x8x国产|