亲宝软件园·资讯

展开

Python简化代码技巧

海拥 人气:0

大家好,我是海拥,在今天的博客中,我们将讨论 Python 中简化代码的技巧。我清楚地记得当我选择学习 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 iter2]

16. 输出不换行

优化前

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

优化后

print(*range(1,5))

17.类

优化前

class School(): 
    fun = {}

优化后

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)

结论

希望大家能从这篇文章中学到一些新的东西,因为我自己也了解了一些我之前不知道的很酷的技巧和单行代码。

加载全部内容

相关教程
猜你喜欢
用户评论