搜尋
首頁後端開發Python教學初學者必看的Python技巧

初學者必看的Python技巧

Mar 17, 2017 pm 03:51 PM
Python直力

以下是我近年來收集的一些Python實用技巧和工具,希望能對你有幫助。

交換變數

x = 6
y = 5
x, y = y, x
print x
>>> 5
print y
>>> 6

if 語句在行內

print "Hello" if True else "World"
>>> Hello

連線

下面的最後一種方式在綁定兩個不同類型的物件時顯得很cool。

nfc = ["Packers", "49ers"]
afc = ["Ravens", "Patriots"]
print nfc + afc
>>> ['Packers', '49ers', 'Ravens', 'Patriots']
 
print str(1) + " world"
>>> 1 world
 
print `1` + " world"
>>> 1 world
 
print 1, "world"
>>> 1 world
print nfc, 1
>>> ['Packers', '49ers'] 1

數字技巧

#除后向下取整
print 5.0//2
>>> 2
# 2的5次方
print 2**5
>> 32

注意浮點數的除法

print .3/.1
>>> 2.9999999999999996
print .3//.1
>>> 2.0

數值比較

這是我見過諸多語言中很少有的如此棒的簡單方法

x = 2
if 3 > x > 1:
   print x
>>> 2
if 1  0:
   print x
>>> 2

同時迭代兩個列表

nfc = ["Packers", "49ers"]
afc = ["Ravens", "Patriots"]
for teama, teamb in zip(nfc, afc):
     print teama + " vs. " + teamb
>>> Packers vs. Ravens
>>> 49ers vs. Patriots

帶索引的列表迭代

teams = ["Packers", "49ers", "Ravens", "Patriots"]
for index, team in enumerate(teams):
    print index, team
>>> 0 Packers
>>> 1 49ers
>>> 2 Ravens
>>> 3 Patriots

列表推導式

已知一個列表,我們可以刷選出偶數列表方法:

numbers = [1,2,3,4,5,6]
even = []
for number in numbers:
    if number%2 == 0:
        even.append(number)

轉換成如下:

numbers = [1,2,3,4,5,6]
even = [number for number in numbers if number%2 == 0]

是不是很牛呢,哈哈。

字典推導

和列表推導類似,字典可以做同樣的工作:

teams = ["Packers", "49ers", "Ravens", "Patriots"]
print {key: value for value, key in enumerate(teams)}
>>> {'49ers': 1, 'Ravens': 2, 'Patriots': 3, 'Packers': 0}

初始化列表的值

items = [0]*3
print items
>>> [0,0,0]

列表轉換為字串

teams = ["Packers", "49ers", "Ravens", "Patriots"]
print ", ".join(teams)
>>> 'Packers, 49ers, Ravens, Patriots'

從字典中取得元素

我承認try/except程式碼並不雅緻,不過這裡有一個簡單方法,嘗試在字典中尋找key,如果沒有找到對應的alue將用第二個參數設為其變數值。

data = {'user': 1, 'name': 'Max', 'three': 4}
try:
   is_admin = data['admin']
except KeyError:
   is_admin = False

取代誠這樣:

data = {'user': 1, 'name': 'Max', 'three': 4}
is_admin = data.get('admin', False)

取得清單的子集

有時,你只需要清單中的部分元素,這裡是一些取得清單子集的方法。

x = [1,2,3,4,5,6]
#前3个
print x[:3]
>>> [1,2,3]
#中间4个
print x[1:5]
>>> [2,3,4,5]
#最后3个
print x[3:]
>>> [4,5,6]
#奇数项
print x[::2]
>>> [1,3,5]
#偶数项
print x[1::2]
>>> [2,4,6]

60個字元解決FizzBu​​zz

前段時間Jeff Atwood 推廣了一個簡單的程式設計練習叫FizzBu​​zz,問題引用如下:

寫一個程序,列印數字1到100,3的倍數列印“Fizz”來替換這個數,5的倍數列印“Buzz”,對於既是3的倍數又是5的倍數的數字打印“FizzBu​​zz”。

這裡就是一個簡短的,有意思的方法解決這個問題:

for x in range(101): print"fizz"[x%3*4::]+"buzz"[x%5*4::] or x

集合

除了python內建的資料型別外,在collection模組同樣也包括一些特別的用例,在有些場合Counter非常實用。如果你參加過這一年的Facebook HackerCup,你甚至能找到他的實用之處。

from collections import Counter
print Counter("hello")
>>> Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})

 迭代工具

和collections函式庫一樣,還有一個函式庫叫itertools,對某些問題真能有效率地解決。其中一個用例是查找所有組合,他能告訴你在一個組中元素的所有不能的組合方式

from itertools import combinations
teams = ["Packers", "49ers", "Ravens", "Patriots"]
for game in combinations(teams, 2):
    print game
>>> ('Packers', '49ers')
>>> ('Packers', 'Ravens')
>>> ('Packers', 'Patriots')
>>> ('49ers', 'Ravens')
>>> ('49ers', 'Patriots')
>>> ('Ravens', 'Patriots')
False == True

比起實用技術來說這是一個很有趣的事,在python中,True和False是全域變量,因此:

False = True
if False:
   print "Hello"
else:
   print "World"
>>> Hello

以上是初學者必看的Python技巧的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python:深入研究彙編和解釋Python:深入研究彙編和解釋May 12, 2025 am 12:14 AM

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

Python是一種解釋或編譯語言,為什麼重要?Python是一種解釋或編譯語言,為什麼重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

對於python中的循環時循環與循環:解釋了關鍵差異對於python中的循環時循環與循環:解釋了關鍵差異May 12, 2025 am 12:08 AM

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

循環時:實用指南循環時:實用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

Python:它是真正的解釋嗎?揭穿神話Python:它是真正的解釋嗎?揭穿神話May 12, 2025 am 12:05 AM

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

與同一元素的Python串聯列表與同一元素的Python串聯列表May 11, 2025 am 12:08 AM

concatenateListSinpythonWithTheSamelements,使用:1)operatoTotakeEpduplicates,2)asettoremavelemavphicates,or3)listcompreanspherensionforcontroloverduplicates,每個methodhasdhasdifferentperferentperferentperforentperforentperforentperfornceandordorimplications。

解釋與編譯語言:Python的位置解釋與編譯語言:Python的位置May 11, 2025 am 12:07 AM

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允許ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

循環時:您什麼時候在Python中使用?循環時:您什麼時候在Python中使用?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中