坐地鐵,就能學會的100個 “非常有用” 的Python技巧【一】
作者:Fatos Morina 編譯:ronghuaiyang

1. ?“for” 循環(huán)中的“Else”條件
numbers?=?[2,?4,?6,?8,?1]
for?number?in?numbers:
????if?number?%?2?==?1:
????????print(number)
????????break
else:
????print("No?odd?numbers")
2. 使用命名的變量從列表中取元素
my_list?=?[1,?2,?3,?4,?5]
one,?two,?three,?four,?five?=?my_list
3. 使用heapq從列表中獲取最大或最小的元素
import?heapq
scores?=?[51,?33,?64,?87,?91,?75,?15,?49,?33,?82]
print(heapq.nlargest(3,?scores))??#?[91,?87,?82]
print(heapq.nsmallest(5,?scores))??#?[15,?33,?33,?49,?51]
4. 把列表中的值作為參數(shù)傳遞給方法
my_list?=?[1,?2,?3,?4]
print(my_list)??#?[1,?2,?3,?4]
print(*my_list)??#?1?2?3?4
def?sum_of_elements(*arg):
????total?=?0
????for?i?in?arg:
????????total?+=?i
????return?total
result?=?sum_of_elements(*[1,?2,?3,?4])
print(result)??#?10
5. 獲取列表的所有中間元素
_,?*elements_in_the_middle,?_?=?[1,?2,?3,?4,?5,?6,?7,?8]
print(elements_in_the_middle)??#?[2,?3,?4,?5,?6,?7]
6. 一行賦值多個變量
one,?two,?three,?four?=?1,?2,?3,?4
7. 列表推導
numbers?=?[1,?2,?3,?4,?5]
squared_numbers?=?[num?*?num?for?num?in?numbers]
print(squared_numbers)
dictionary?=?{'a':?4,?'b':?5}
squared_dictionary?=?{key:?num?*?num?for?(key,?num)?in?dictionary.items()}
print(squared_dictionary)??#?{'a':?16,?'b':?25}
8. 通過Enum枚舉相同概念的相關項
Enum是綁定到唯一值的一組符號名。它們類似于全局變量,但它們提供了更有用的repr()、分組、類型安全和其他一些特性。
from?enum?import?Enum
class?Status(Enum):
????NO_STATUS?=?-1
????NOT_STARTED?=?0
????IN_PROGRESS?=?1
????COMPLETED?=?2
print(Status.IN_PROGRESS.name)??#?IN_PROGRESS
print(Status.COMPLETED.value)??#?2
9. 不使用循環(huán)來重復字符串
name?=?"Banana"
print(name?*?4)??#?BananaBananaBananaBanana
10. 像數(shù)學式子一樣比較3個數(shù)字
1?10
11. 在單條語句中合并字典
first_dictionary?=?{'name':?'Fatos',?'location':?'Munich'}
second_dictionary?=?{'name':?'Fatos',?'surname':?'Morina','location':?'Bavaria,?Munich'}
result?=?first_dictionary?|?second_dictionaryprint(result)??#?{'name':?'Fatos',?'location':?'Bavaria,?Munich',?'surname':?'Morina'}
12. 在tuple中找到元素的索引
books?=?('Atomic?habits',?'Ego?is?the?enemy',?'Outliers',?'Mastery')
print(books.index('Mastery'))???#?3
13. 把字符串列表轉換成一個列表
input?=?"[1,2,3]"
input?=?[1,2,3]
input?=?[[1,?2,?3],?[4,?5,?6]]
import?ast def?string_to_list(string):????????
????return?ast.literal_eval(string)
import?ast
def?string_to_list(string):
????return?ast.literal_eval(string)
string?=?"[[1,?2,?3],[4,?5,?6]]"
my_list?=?string_to_list(string)
print(my_list)??#?[[1,?2,?3],?[4,?5,?6]]
14. 使用命名參數(shù)避免 “trivial” 錯誤
a?-?b?!=?b?-a
def?subtract(a,?b):
????return?a?-?b
print((subtract(1,?3)))??#?-2
print((subtract(3,?1)))??#?2
def?subtract(a,?b):
????return?a?-?b
print((subtract(a=1,?b=3)))??#?-2
print((subtract(b=3,?a=1)))??#?-2
15. 使用單個print()語句打印多個元素
print(1,?2,?3,?"a",?"z",?"this?is?here",?"here?is?something?else")
16. 一行打印多個元素
print("Hello",?end="")
print("World")??#?HelloWorld
print("Hello",?end="?")
print("World")??#?Hello?World
print('words',???'with',?'commas',?'in',?'between',?sep=',?')
#?words,?with,?commas,?in,?between
17. 打印多個值,每個值之間使用自定義分隔符
print("29",?"01",?"2022",?sep="/")??#?29/01/2022
print("name",?"domain.com",?sep="@")??#[email protected]
18. 不能在變量名的開頭使用數(shù)字
four_letters?=?“abcd”?#?this?works4_letters?=?“abcd”?#?this?doesn’t?work
19. 不能在變量名的開頭使用操作符
+variable?=?“abcd”??#?this?doesn’t?work
20. 你不能把0作為數(shù)字的第一個數(shù)字
number?=?0110?#?this?doesn't?work
21. 你可以在變量名的任何位置使用下劃線字符
a______b?=?"abcd"??#?this?works
_a_b_c_d?=?"abcd"??#?this?also?works
22. 可以用下劃線分隔較大的數(shù)字
print(1_000_000_000)??#?1000000000
print(1_234_567)??#?1234567
23. 顛倒列表的順序
my_list?=?['a',?'b',?'c',?'d']
my_list.reverse()
print(my_list)??#?['d',?'c',?'b',?'a']
24. 使用step函數(shù)對字符串切片
my_string?=?"This?is?just?a?sentence"
print(my_string[0:5])??#?This
#?Take?three?steps?forward
print(my_string[0:10:3])??#?Tsse
25. 反向切片
my_string?=?"This?is?just?a?sentence"
print(my_string[10:0:-1])??#?suj?si?sih
#?Take?two?steps?forward
print(my_string[10:0:-2])??#?sjs?i
26. 只有開始或結束索引的部分切片
my_string?=?"This?is?just?a?sentence"
print(my_string[4:])??#?is?just?a?sentence
print(my_string[:3])??#?Thi
27. Floor 除法
print(3/2)??#?1.5
print(3//2)??#?1
28. == 和 “is” 的差別
first_list?=?[1,?2,?3]
second_list?=?[1,?2,?3]
#?Is?their?actual?value?the?same?
print(first_list?==?second_list)??#?True
#?Are?they?pointing?to?the?same?object?in?memory
print(first_list?is?second_list)??
#?False,?since?they?have?same?values,?but?in?different?objects?in?memory
third_list?=?first_list
print(third_list?is?first_list)??
#?True,?since?both?point?to?the?same?object?in?memory
29. 更改分配給另一個變量的變量的值
first?=?"An?initial?value"
second?=?first
first?=?"An?updated?value"
print(first)??#?An?updated?value
print(second)??#?An?initial?value
30. 檢查一個字符串是否大于另一個字符串
first?=?"abc"
second?=?"def"
print(first?#?True
second?=?"ab"
print(first?#?False
31. 檢查字符串是不是從特定字符開始的
my_string?=?"abcdef"
print(my_string.startswith("b"))??#?False
32. 使用id()找到變量的唯一id
print(id(1))??#?4325776624
print(id(2))??#?4325776656
print(id("string"))??#?4327978288
33. Integers, floats, strings, booleans, sets以及tuples是不可修改的
number?=?1
print(id(number))??#?4325215472
print(id(1))??#?4325215472
number?=?3
print(id(number))??#?4325215536
print(id(1))??#?4325215472
送你一張我們星球的優(yōu)惠券,目前已經有100多人啦,還有3天就過期了!
歡迎來一起玩Python!
推薦閱讀:
入門:?最全的零基礎學Python的問題? |?零基礎學了8個月的Python??|?實戰(zhàn)項目?|學Python就是這條捷徑
干貨:爬取豆瓣短評,電影《后來的我們》?|?38年NBA最佳球員分析?|? ?從萬眾期待到口碑撲街!唐探3令人失望? |?笑看新倚天屠龍記?|?燈謎答題王?|用Python做個海量小姐姐素描圖?|碟中諜這么火,我用機器學習做個迷你推薦系統(tǒng)電影
趣味:彈球游戲? |?九宮格? |?漂亮的花?|?兩百行Python《天天酷跑》游戲!
AI:?會做詩的機器人?|?給圖片上色?|?預測收入?|?碟中諜這么火,我用機器學習做個迷你推薦系統(tǒng)電影
小工具:?Pdf轉Word,輕松搞定表格和水??!?|?一鍵把html網頁保存為pdf!|??再見PDF提取收費!?|?用90行代碼打造最強PDF轉換器,word、PPT、excel、markdown、html一鍵轉換?|?制作一款釘釘?shù)蛢r機票提示器!?|60行代碼做了一個語音壁紙切換器天天看小姐姐!|
年度爆款文案
評論
圖片
表情

