1. 程式人生 > 實用技巧 >Python內建資料型別

Python內建資料型別

數值型

  int

  float

  complex

  bool

數字的處理函式

round();四捨六入,五取偶;round(1.5)=2;round(2.5)=2;

floor()地板;天花板ceil(); math.floor(1.5)=1;math.ceil(1.5)=2;

min()

max()

pow(x,y); 等於x**y;pow(3,2)=3**2=9

math.sqrt();開平方;math.sqrt(9)=3

進位制函式,返回值是字串;

  bin();二進位制;bin(10)="0b1010"

  oct();八進位制;

  hex();十六進位制;

型別判斷

  type(obj);

type(3)

  isinstance(obj,class_or_tuple);isinstance(3,int); isinstance(3,(int,str))

列表list []  

  列表是可變的

  列表索引/下標訪問

  列表查詢某元素索引位置,起止索引為可選項; index(value,[start,[stop]]);a=[3,2,1,0];a.index(5);找尋列表a中5元素的位置;

  列表計算某值出現次數;a.count(3)

  時間複雜度;O(1),O(n)等;

  列表元素個數/長度len();len(a);

  列表元素修改;list[index]=value;a[1]=33;

  列表增加,插入元素;

    append(object)-->None;沒有返回值,就地修改;增加一個元素,返回None

    insert(index,object)-->None;索引超上下界可以?超越上界,尾部追加;超越下界,頭部新增;

  + ;a+[3,2,1];

  *;a*5;

  列表刪除元素;

    remove(value)-->None;從左至右刪除第一個;

    pop([index])-->item;不指定索引,就是刪除列表最後一個元素;指定索引,索引值被刪除;

    clear()-->None;清除列表所有元素,剩餘[]

  列表反轉;reverse()-->None;

  列表排序;sort();預設升序 等價於 sort(reverse=False) ;reverse=True,反轉,降序;sort(key=None,reverse=False);

  in;3 in [3,2,1];3 not in [3,2,1];

  列表複製;

    a=list(range(4))

    b=a.copy(); id(a);a==b,(內容相等)True; a is b,(地址相等)False;

  淺拷貝a.copy(),深拷貝copy.deepcopy(a);

隨機數

  random模組,random.randint(a,b) 返回[a,b]之間的整數

  random.choice(seq);隨機挑選;random.choice([1,3,5,2]);random.choice([0,1])

  random.randrange([start],stop,[,step]); 前閉後開;

  random.shuffle(list);就地打亂列表元素;

元組tuple

  元組是不可變物件;只讀

  tuple()

  

#求100以內的質數
import math
a=[2]
for i in range(3,100,2):
    for j in range(3,int(math.sqrt(i))+1,2):
        if i%j==0:
            print(i)
            break
    else:
        a.append(i)
print(a)
print(len(a))
#計算楊輝三角前6行
#第n行有n項,n是正整數
#第n行數字之和為2**(n-1)
n=8
c=[]
print((n//2+3)*" ",end='')
print([1])
for i in range(1,n-1):#2,3,4
    b=[1] #c=[1,1],[1,2,1],[1,3,3,1],
    for j in range(1,i):#1,[1,2],[1,2,3]
       b.append(c[j-1]+c[j]) #2,[3,3],[4,6,4]
    b.append(1)
    c=b
    print((n//2+3-i)*" ",end="")
    print(c)