天天看點

18 個 Python 技巧幫助你簡化代碼

大家好,我是海擁,在今天的部落格中,我們将讨論 Python 中簡化代碼的技巧。我清楚地記得當我選擇學習 python 時,最令我震驚的是它的簡單性和可讀性。但是你知道還可以用更少的代碼行可以讓 Python 代碼變得更簡單嗎?是的!沒錯!下面這些單行代碼可以為你節省大量時間和記憶體,讓我們一起來看看吧。

什麼是單行代碼?

你可以将單行代碼視為壓縮在一起的代碼塊,使其适合一行。它是隻包含在一行中的簡潔、有用的程式。

為什麼我需要它們?

如果你并不喜歡寫單行代碼,或者你隻是好奇為什麼我們必須知道這些,那麼下面是一些非常有說服力的理由。

  • 了解 One-liners 将使你成為 Python 專家,因為你将更好地了解該語言。
  • 這将幫助你更快地編寫代碼。你可以比其他人更快地編寫一段代碼,這将有助于你進行競争性程式設計。
  • 線上課程将提高你的基礎知識和程式設計基礎,因為它們會加強你的基礎知識。
  • 你将更多地以 Pythonic 方式編寫代碼。通常,來自不同語言的人經常在 Python 中以非 Python 的方式編寫代碼,例如他們不使用清單推導、多重指派和切片等。
  • 你可以給你的朋友、同僚留下深刻的印象,如果你掌握了單行的話,你可以在面試中給人留下好印象。

開始

1.if-else

優化前

if 3 < 2:
    var=21
else:
    var=42      

優化後

var = 21 if 3<2 else 42      

2. elif

優化前

>>> x = 42
>>> if x > 42:
>>>     print("no")
>>> elif x == 42:
>>>     print("yes")
>>> else:
>>>     print("maybe")
yes      

優化後

>>> print("no") if x > 42 else print("yes") if x == 42 else print("maybe")
yes      

3. if

優化前

condition = True

if condition:
    print('hi')      

優化後

if condition: print('hello')
print('hello') if condition else None      

4.函數

優化前

def f(x):
    return "hello "+ x      

優化後

f = lambda x: "hello "+ x
f = exec("def f(x):\n    return 'hello '+ x")      

5.循環(清單推導式)

優化前

squares = []
for i in range(10):
    squares.append(i**2)      

優化後

squares=[i**2 for i in range(10)]      

6. if 循環

優化前

squares = []
for i in range(10):
    if i%2==0:
        squares.append(i**2)      

優化後

squares = [i**2 for i in range(10) if i%2==0]      

7. if else 循環

優化前

squares = []
for i in range(10):
    if i%2==0:
        squares.append(i**2)
    else:
        squares.append(False)      

優化後

squares = [i**2 if i%2==0 else False for i in range(10)]      

8. While 循環與 if else

優化前

c=0
while c < 10:
    if c!=5:
        print(c)
    else:
        print("FIVE")
    c+=1      

優化後

while c < 10: c+=1; print(c) if c!=5 else print("FIVE")      

9. 變量交換

優化前

>>> def swap(x,y):
    x = x ^ y
    y = x ^ y
    x = x ^ y
    return x, y
>>> swap(10,20)
(20,10)      

優化後

>>> x, y = 10, 20
>>> x, y = y, x
(20, 10)      

10. 多重指派

優化前

a="ONE"
b=2
c=3.001      

優化後

a, b, c = "One", 2, 3.001      

11. 将字元串寫入檔案

優化前

text = "Helllloooooo"
fileName = "hello.txt"
f=open(fileName, "a")
f.write(text)
f.close()      

優化後

text = "Helllloooooo"
fileName = "hello.txt"
print(text, file=open(fileName, 'a'))      

12.快速排序

優化前

def partition(array, start, end):
    pivot = array[start]
    low = start + 1
    high = end

    while True:
        while low <= high and array[high] >= pivot:
            high = high - 1

        while low <= high and array[low] <= pivot:
            low = low + 1

        if low <= high:
            array[low], array[high] = array[high], array[low]
        else:
            break

    array[start], array[high] = array[high], array[start]

    return high

def quick_sort(array, start, end):
    if start >= end:
        return

    p = partition(array, start, end)
    quick_sort(array, start, p-1)
    quick_sort(array, p+1, end)

array = [29,99,27,41,66,28,44,78,87,19,31,76,58,88,83,97,12,21,44]

quick_sort(array, 0, len(array) - 1)
print(array)      

優化後

array = [29,99,27,41,66,28,44,78,87,19,31,76,58,88,83,97,12,21,44]
q = lambda l: q([x for x in l[1:] if x <= l[0]]) + [l[0]] + q([x for x in l if x > l[0]]) if l else []
print(q(array))      

13. 斐波那契數列

優化前

def fib(x):
    if x <= 2:
        return 1
    return fib(x - 1) + fib(x - 2)      

優化後

fib=lambda x: x if x<=1 else fib(x-1) + fib(x-2)      

14. HTTP 伺服器

優化前

import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()      

優化後

python -m http.server 8000      

15. 嵌套 For 循環

優化前

iter1 = [1, 2, 3, 4]
iter2 = ['a', 'b', 'c']
for x in iter1:
    for y in iter2:
        print(x, y)      

優化後

[print(x, y) for x in iter1 for y in      

16. 輸出不換行

優化前

for i in range(1,5):
    print(i, end=" ")      

優化後

print(*range(1,5))      

17.類

優化前

class School():      

優化後

School = type('School', (object,), {'fun':{}})      

18. 海象運算符:=(Python 3.8)

優化前

command = input("> ")
while command != "quit":
    print("You entered:", command)      
while (command := input("> ")) != "quit": print("You entered:", command)      

結論