初學Python的一些細節

1、python的數據類型java

  1.python的基本數據類型包括數值數據類型和字符串數據類型;基本數據類型的特色是不容許改變,若是改變基本數據類型的值,會致使內存的從新分配。python

intc++

整形git

    二進制    a = 0b1010app

   八進制    a = 0o37dom

  十進制    a = 25函數

   十六進制   a = 0x34aui

floatspa

浮點型code

f1 = 0.12,f2 = 1.343e-3

bool

布爾型

flag = True  

complex

複數類型

a = complex(2,3)

  2.數值的相互轉換函數

轉十六進制

hex()

轉八進制

oct()

轉二進制

bin()

轉整形

int()

  3.變量的三個屬性

標識

變量的內存地址,能夠用id()查看

類型

變量的類型,能夠用type()查看

存儲的值

  4.判斷某個變量是不是某種類型實例

print(isinstance(3, float))            #False

  5.複數類型的使用

a = complex(2,2)
b = complex("3+2j")
print(a)
print(b)
print(a+b)
print(a-b)
print(a*b)
print(a/b)

(2+2j)
(3+2j)
(5+4j)
(-1+0j)
(2+10j)
(0.7692307692307692+0.15384615384615388j)

   6.python的字符串類型不像Java能夠與數值類型相加,如「str」+1會報錯,但python支持字符串與數值相乘,表示將字符串重複多少次。

#報錯
#print("str"+1)
#重複字符串 print("The life is short,i love python\n" * 3) #The life is short,i love python #The life is short,i love python #The life is short,i love python
#轉爲大寫 print("lower".upper()) #LOWER
#轉爲小寫 print("UPPER".lower()) #upper

#去除前導和尾部空白 print(" hello python ".strip()) #hello python

#也能夠指定去除的字符 print("##hello python##!".strip("#!")) #hello python

#求長度 print(len("hello")) #5

#拆分字符串 print("orange banana apple".split(" ")) #['orange', 'banana', 'apple']

#用指定字符串鏈接一個列表 print(" ".join(["orange","apple","banana","peach"])) #orange apple banana peach

#判斷字符串是否以某個子串開始 print("good good study".startswith("go")) #True

#判斷字符串是否以某個子串開始 print("day day up".endswith("up")) #True

#統計子串出現次數 print("Python is a nascent programming language.".count("p")) #1

#查找子串出現的下標 print("Sometimes your whole life boils down to one insane move.".find("wh")) #15

#判斷是不是數字 print("moive".isdigit()) #False

#判斷是不是字母 print("money".isalpha()) #True

#判斷是不是空格 print("i declared".isspace()) #False

  7.Python的字符串最強大之處是切片操做

str = "Attitude determines altitude."
#取出Attitude(外國人的習慣是左閉右開,即包括左下標,不包括右下標)

print(str[0:9]) #Attitude

print(str[0:20:3]) #Aiddeis (每3個取一個)

print(str[-5:-1]) #tude

  8.Python的字符串能夠用單引號,雙引號,三引號表示,但字符串跨行時只能用三引號或反斜槓

str = '''Be
a
laborious
bee
'''

print(str) str1 = "Be \ a \ hard-working \ man" print(str1) #Be a hard-working man

  9.實現字符串反轉

#切片 str[開始位置:結束位置:步數] 將步數設爲-1
def strReverse1(str):
    return str[::-1]
#將字符串轉爲列表,反轉後再鏈接爲字符串 def strReverse2(str): newList = list(str) newList.reverse() return "".join(newList)
print(strReverse1("python")) print(strReverse2("python"))

2、輸入輸出

  一、輸入函數input()

#輸入一個字符串
myStr = input("請輸入一個字符串:")
print(myStr)


#以逗號分割輸入多個數
a,b,c = eval(input("請輸入3個數:"))
print(a,b,c)

  2.輸出函數 print()

#以逗號分割輸出多個變量,輸出後顯示的分隔符是空格,結尾會輸出一個換行符
print("i","am","studying","python")        #i am studying python

#指定分隔符和結尾符
print("i","am","studying","python",sep="#",end=" ")
print()

#相似c語言的輸出
name = "jackson"
age = 22
salary = 5000.0
print("name:%s,age:%d,salary:%.3f" % (name,age,salary))

#python特有的輸出形式
print("I like eating {} and {}".format("banana", "pear"))  #按位置填充
print("His name is {name} and he is a {sex}".format(sex='male',name='judy'))   #按具體名字填充
print("{1} can arm our {0}".format("brain","knowledge"))                       #按編號填充
print("The happiness rate of chinese citizen is up to {:.3f}".format(0.45))    #設置浮點數輸出格式爲小數點後三位
print("The population of china is {:,d} million".format(1300))                 #千分位用逗號表示

3、集合數據類型 

  Python的集合數據類型包括列表,元組,字典,集合

列表

list(內部元素能夠從新賦值,列表和列表能夠相加,列表和數字能夠相乘)

arr = ["jack"]

元組

tuple(內部元素不能從新賦值,元組能夠和元組相加,元組能夠和數字相乘)

myTuple = ("nacy","rose")

字典

dict(無序,可從新賦值,鍵惟一,值不惟一,鍵爲不可變元素)

myMap = {"name":"zhangshan","age":12}

集合

set(無序,惟一,可進行集合間的交併差補)

mySet1= set(["judy","tom","martin"]) mySet2 = set("lily")

  1.列表

#四種遍歷方式
fruits = ["orange","banana","pear","peach"]
for item in fruits: print(item,end=" ") print() for item in iter(fruits): print(item,end=" ") print() for i,item in enumerate(fruits): print(i,"===>",item,end=" ") print() for item in range(len(fruits)): print(fruits[item],end=" ") print() #重複列表四次 print(fruits*4) #['orange', 'banana', 'pear', 'peach', 'orange', 'banana', 'pear', 'peach', 'orange', 'banana', 'pear', 'peach', 'orange', 'banana', 'pear', 'peach'] #列表鏈接 print(fruits+["pineapple","apple"]) #刪除指定下標的元素,不提供參數則刪除表尾元素 print(fruits.pop(2)) #['orange', 'banana', 'pear', 'peach', 'pineapple', 'apple'] #追加元素 append追加和extend追加有區別 #append追加的是列表 #extend追加的是元素 fruits.append(["Coconut"]) print(fruits) #['orange', 'banana', 'peach', ['Coconut']] fruits.pop() fruits.extend(["Coconut"]) print(fruits) #['orange', 'banana', 'peach', 'Coconut'] #列表反轉 fruits.reverse() print(fruits) #['Coconut', 'peach', 'banana', 'orange'] #指定位置插入 fruits.insert(2, "nothing") print(fruits) #['Coconut', 'peach', 'nothing', 'banana', 'orange'] #刪除列表切片 del fruits[1:3] print(fruits) #['Coconut', 'banana', 'orange']

  2.元組

myTuple1 = ("bird","plane","vehicle","subway")

#不能對單個元素從新賦值(報錯)
#myTuple1[0] = "parrot"

#但能夠對整個元組賦值
myTuple1 = ("python","c++","java")
print(myTuple1)                     #('python', 'c++', 'java')

#建立空元組
emptyTuple = ()
print(emptyTuple)                   #()


#注意建立一個元素的元組要在結尾加逗號
oneTuple = (1)
print(oneTuple)                     #1 不加逗號編譯器會認爲括號是進行算數運算,而不是建立元組
oneTuple = (1,)
print(oneTuple)                     #(1,)

#元組的取值 
print(myTuple1[0])                  #python
print(myTuple1[:])                  #('python', 'c++', 'java')
print(myTuple1[:1])                 #('python',)
print(myTuple1[len(myTuple1)-1:])   #('java',)

#元組的重複 
print(myTuple1 *4)                  #('python', 'c++', 'java', 'python', 'c++', 'java', 'python', 'c++', 'java', 'python', 'c++', 'java')

#元組相加
print(myTuple1 + ("one","two","three"))  #('python', 'c++', 'java', 'one', 'two', 'three')

  3.字典

myDict = {"one":1,"two":343.33,"three":True}

#字典的取值
print(myDict["one"])       #1

#判斷鍵是否存在
print("three" in myDict)   #True


#更新值
myDict["one"] = 100
print(myDict)              #{'one': 100, 'two': 343.33, 'three': True}

#清空字典
myDict.clear()
print(myDict)              #{}

  4.集合

#以字符串建立set,自動去除重複元素
mySet = set("hello")
print(mySet)                  #{'o', 'l', 'e', 'h'}


#以list建立set
mySet1 = set(["a","m","e","o"])
print(mySet1)                 #{'o', 'a', 'm', 'e'}

#以map建立set,值爲map的鍵
mySet2 = set({"name":1,"age":2})
print(mySet2)                 #{'name', 'age'}

#交集
print(mySet & mySet1)         #{'e', 'o'}

#並集
print(mySet | mySet1)         #{'l', 'a', 'e', 'h', 'm', 'o'}

#差集
print(mySet - mySet1)         #{'l', 'h'}

#對稱差分運算
print(mySet ^ mySet1)         #{'l', 'a', 'h', 'm'}

4、強大的列表解析功能

import random
#列表解析
#生成10個隨機數,返回一個新列表
list1 = [random.randint(0,100) for i in range(0,10)]
for item in list1:
    print(item,end=" ")         #74 38 75 45 96 1 38 93 58 80 
print()
 #求1到20的平方組成的列表    
list2 = [i*i for i in range(1,21)]
for num in list2:                      
    print(num,end=" ")          #1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400
     
#選出list2中的偶數
list3 = [i for i in list2 if i % 2 == 0]
for num in list3:
    print(num)                  #4 16 36 64 100 144 196 256 324 400
 
#按行遍歷矩陣
list4 = [[1,2,3,4],[5,6,7,8],[2,3,4,5],[6,7,8,9]]
list5 = [[1,4,5,6],[2,1,3,4],[3,4,2,1],[7,8,2,1]]
print([row for row in list4])   #[[1, 2, 3, 4], [5, 6, 7, 8], [2, 3, 4, 5], [6, 7, 8, 9]]
 
#按列遍歷矩陣
print([list4[row][1] for row in range(len(list4))])  #[2, 6, 3, 7]
 
#遍歷對角線
print([list4[i][i] for i in range(len(list4))])      # [1, 6, 4, 9]
 
#逐個遍歷
print([list4[row][col] for row in range(len(list4)) for col in range(len(list4[row]))])  #[1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 4, 5, 6, 7, 8, 9]
 
 
#矩陣相加
print([list4[row][col] + list5[row][col] for row in range(list4.__len__()) for col in range(list4[row].__len__())])
#[2, 6, 8, 10, 7, 7, 10, 12, 5, 7, 6, 6, 13, 15, 10, 10]


#轉置矩陣
print([row for row in zip(*list4)])  #[(1, 5, 2, 6), (2, 6, 3, 7), (3, 7, 4, 8), (4, 8, 5, 9)]
 
#求最大長度對應的字符
students = ["jack","shirely","kangkang","mary"]
maxLen = max([len(item) for item in students])
print(maxLen)
maxStr = [temp for temp in students if len(temp) == maxLen]
print(maxStr)                                     #['kangkang']

5、內置函數

#幾個內置的高階函數 map,filter,reduce,sorted
#map用於將一函數規則應用於一可迭代集合的全部元素
#reduce用於將一函數規則反覆做用於一可迭代集合的元素,傳入的函數參數必須爲兩個
#filter將一可迭代集合中適用於函數規則的元素挑選出來
#sorted用於對可迭代集合進行排序

#map的一個栗子(將字符串轉爲對應數字)
#匿名函數求對應字符的數字表示如'0'對應數字0,'1'對應1
f = lambda ch:{"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9}[ch]
#上面函數的功能與這個同樣 f1
= lambda ch:int(ch)
print(list(map(f,"322"))) #[3, 2, 2] #reduce的一個栗子(將字符串轉換爲對應的十進制數) def str2Decimal(x,y): return x*10 + y print(reduce(str2Decimal,map(f,"232"))) #232 #filter的一個栗子(使用埃氏篩選法篩選素數) seq = range(2,51) for i in seq: f = lambda x : x == i or x % i seq = list(filter(f,seq)) print(list(seq)) #[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] #sorted的一個栗子 rules = lambda x:x.lower() reles2 = lambda x:x["age"] students = ["jack","Nacy","Kangkang","asia"] aMap = [{"name":"kangknag","age":25},{"name":"ag","age":13},{"name":"wnag","age":23}] newlist = sorted(students, key=rules, reverse=False) print(sorted(aMap,key=reles2)) #[{'name': 'ag', 'age': 13}, {'name': 'wnag', 'age': 23}, {'name': 'kangknag', 'age': 25}] print(newlist) #['asia', 'jack', 'Kangkang', 'Nacy']

先寫到這吧,有點累。。。

相關文章
相關標籤/搜索