溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

初學者應該掌握的Python技巧

發布時間:2020-11-25 11:36:22 來源:億速云 閱讀:143 作者:小新 欄目:編程語言

小編給大家分享一下初學者應該掌握的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]

集合

除了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技巧有了一定的了解,想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女