25條實用簡潔的python程式碼,拿走即用(真乾貨)

語言: CN / TW / HK

經常寫程式碼的大佬一定有自己私藏的非常好用的程式碼段對不對?

雖然我不算什麼大佬,但是我擅長蒐集資訊啊,通過我的努力,我從網際網路上搜集整理了25個常用的Python程式碼段,分享給需要的人。

你想問為什麼是Python麼?

其實,選擇Python也不是沒有理由的。

1,Python的前景非常好:Guido龜叔表示:他打算在2022年10月釋出3.11版本時將快CPython的速度提高1倍。在接下來的四年裡,他的目標是將CPython的速度提高到原來的5倍。

2,Python 的用法非常簡潔、靈活:它的擴充套件庫也很豐富,可以滿足非常多複雜場景的需求,能夠替代非常多的手工操作。

3,Python跨平臺性非常好:無論是在 macOS 和 Windows 間如何切換,不用修改任何一行程式碼,就可以讓已經寫好的程式直接在新的平臺上執行。

好了,廢話就不多說了。

總之,在職場總有人不需要加班就能完成老闆佈置的工作任務,那麼那個人為什麼不能是你?

所以,今天整理的25個常用的Python程式碼段請果斷收藏起來,如果覺得足夠好用記得分享給你身邊的朋友和同事喲~

1交換兩個變數的值

num_1, num_2 = 666, 999
# 一行程式碼搞定交換兩個變數的值
num_1, num_2 = num_2, num_1
print(num_1, num_2)
輸出:
999 666

Process finished with exit code 0

2查詢物件使用的記憶體

import sys

slogan = "今天你學python了麼?"
size = sys.getsizeof(slogan)
print(size)
輸出:
100

Process finished with exit code 0

3反轉字串

slogan = "今天你學習python了麼?"
# 一行程式碼搞定字串的反轉
new_slogan = slogan[::-1]
print(new_slogan)
輸出:
?麼了nohtyp習學你天今
Process finished with exit code 0

4檢查字串是否為迴文

# 定義一個判斷字串是否是迴文的函式
def is_palindrome(string):
    return string == string[::-1]

示例:呼叫判斷函式來進行判斷slogan是否是迴文字串
slogan = "今天你學python了麼?"
_ = is_palindrome(slogan)
print(_)
輸出:
False

Process finished with exit code 0

5將字串列表合併為單個字串

slogan = ["今", "天", "你", "學", "python", "了", "麼", "?"]
# 一行程式碼搞定將字串列表合併為單個字串
real_slogan = "".join(slogan)
print(real_slogan)
輸出:
今天你學python了麼?

Process finished with exit code 0

6查詢存在於兩個列表中任一列表存在的元素

# 定義一個函式用來查詢存在於兩個列表中任一列表存在的元素
def union(list1, list2):
    return list(set(list1 + list2))

示例:呼叫該函式用來查詢存在於兩個列表中任一列表存在的元素
list1, list2 = [5, 2, 0], [5, 2, 1]
new_list = union(list1, list2)
print(new_list)
輸出:
[0, 1, 2, 5]

Process finished with exit code 0

7列印N次字串

slogan = "今天你學python了麼?"
new_slogan = 11*slogan
print(new_slogan)
輸出:
今天你學python了麼?今天你學python了麼?今天你學python了麼?今天你學python了麼?今天你學python了麼?今天你學python了麼?今天你學python了麼?今天你學python了麼?今天你學python了麼?今天你學python了麼?今天你學python了麼?

Process finished with exit code 0

8鏈式比較

number = 100
print(98<number<102)
輸出:
True

Process finished with exit code 0

print(100==number<102)
輸出:
True

Process finished with exit code 0

9單詞大小寫

slogan = "python happy"
# 一行程式碼搞定單詞大小寫轉換
print(slogan.upper())

# 一行程式碼搞定單詞首字母大寫
print(slogan.capitalize())

# 一行程式碼搞定將每個單詞的首字母轉為大寫,其餘小寫
print(slogan.title())
輸出:
PYTHON HAPPY
Python happy
Python Happy

Process finished with exit code 0

10統計列表中元素的頻率

from collections import Counter


numbers = [1, 1, 3, 2, 4, 4, 3, 6]
# 一行程式碼搞定求列表中每個元素出現的頻率
count = Counter(numbers)
print(count)
輸出:
Counter({1: 2, 3: 2, 4: 2, 2: 1, 6: 1})

Process finished with exit code 0

11判斷字串所含元素是否相同

from collections import Counter


course = "python"
new_course = "ypthon"
count_1, count_2 = Counter(course), Counter(new_course)
if count_1 == count_2:
    print("兩個字串所含元素相同!")
輸出:
兩個字串所含元素相同!

Process finished with exit code 0

12將數字字串轉化為數字列表

string = "666888"
numbers = list(map(int, string))
print(numbers)
輸出:
[6, 6, 6, 8, 8, 8]

Process finished with exit code 0

13使用enumerate() 函式來獲取索引-數值對

string = "python"
for index, value in enumerate(string):
    print(index, value)
輸出:
0 p
1 y
2 t
3 h
4 o
5 n

Process finished with exit code 0

14程式碼執行消耗時間

import time

start_time = time.time()

numbers = [i for i in range(10000)]

end_time = time.time()
time_consume = end_time - start_time
print("程式碼執行消耗的時間是:{}".format(time_consume))
輸出示例:
程式碼執行消耗的時間是:0.002994537353515625

Process finished with exit code 0

15比較集合和字典的查詢效率

import time

number = 999999
# 生成數字列表和數字集合
numbers = [i for i in range(1000000)]
digits = {i for i in range(1000000)}

start_time = time.time()
# 列表的查詢
_ = number in numbers
end_time = time.time()

print("列表查詢時間為:{}".format(end_time - start_time))

start_time = time.time()
# 集合的查詢
_ = number in digits
end_time = time.time()

print("集合查詢時間為:{}".format(end_time - start_time))
輸出:
列表查詢時間為:0.060904741287231445
集合查詢時間為:0.0

Process finished with exit code 0

16字典的合併

info_1 = {"apple": 13, "orange": 22}
info_2 = {"爆款寫作": 48, "躍遷": 49}
# 一行程式碼搞定合併兩個字典
new_info = {**info_1, **info_2}
print(new_info)
輸出:
{'apple': 13, 'orange': 22, '爆款寫作': 48, '躍遷': 49}
Process finished with exit code 0

17隨機取樣

import random

books = ["爆款寫作", "這個世界,偏愛會寫作的人", "寫作七堂課", "越書寫越明白"]
# 隨機取出2本書閱讀
reading_book = random.sample(books, 2)
print(reading_book)
輸出:
['這個世界,偏愛會寫作的人', '越書寫越明白']

Process finished with exit code 0

18判斷列表中元素的唯一性

# 定義一個函式判斷列表中元素的唯一性
def is_unique(list):
    if len(list) == len(set(list)):
        return True
    else:
        return False


# 呼叫該函式判斷一個列表是否是唯一性的
numbers = [1, 2, 3, 3, 4, 5]
_ = is_unique(numbers)
print(_)
輸出:
False
Process finished with exit code 0

19計算階乘 遞迴函式實現

def fac(n):
    if n > 1:
        return n*fac(n-1)
    else:
        return 1

number = int(input("n="))
print("result = {}".format(fac(number)) )
輸出:
n=5
result = 120

Process finished with exit code 0

20列出當前目錄下的所有檔案和目錄名

import os


files = [file for file in os.listdir(".")]
print(files)
輸出:
['.idea', '2048.py', 'access.log', 'beautiful_girls', 'beautiful_girls_photos', 'boy.py', 'cache.json', 'catoffice.py', 'cookie.json', 'data.csv', 'data.txt', 'diary', 'files', 'filtered_words.txt', 'geckodriver.log', 'get_movies_info2.py', 'girl.py', 'girl1.py', 'ha.conf', 'homework.py', 'homework3.py', 'index.html', 'info.ini', 'notepad.py', 'rent.csv', 'stock.txt', 'student.txt', 'student.xlsx', 'student_register_info.json', 'test.png', 'test_picture.txt', 'zhihu.html', '__pycache__', '九尾1997_200行程式碼實現2048小遊戲.py', '九尾1997_python實現圖片轉字元畫.py', '九尾1997_實現一個簡單的計算器.py', '九尾1997_爬取優美圖美女寫真.py', '九尾1997_爬取北京58租房資訊.py', '九尾1997_路飛學城註冊頁面', '校園管理系統.py', '爬蟲模擬登入.py', '記事本.m4a']

Process finished with exit code 0

21把原字典的鍵值對顛倒並生產新的字典

dict_1 = {1: "python", 2: "java"}
new_dict = {value:key for key, value in dict_1.items()}
print(new_dict)
輸出:
{'python': 1, 'java': 2}

Process finished with exit code 0

22列印九九乘法表

for i in range(1, 10):
    for j in range(1, i+1):
        print("{} * {} = {}".format(i, j, i*j), end="")
    print()
輸出:
1 * 1 = 1 
2 * 1 = 2 2 * 2 = 4 
3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 
4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16 
5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 
6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30 6 * 6 = 36 
7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49 
8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64 
9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81

Process finished with exit code 0

23計算每個月天數

import calendar

month_days = calendar.monthrange(2025,8)
print(month_days)
輸出:
(4, 31)

Process finished with exit code 0

24隨機生成驗證碼,呼叫隨機模組

import random, string

str_1 = "0123456789"
# str_2 是包含所有字母的字串
str_2 = string.ascii_letters
str_3 = str_1 + str_2
# 多個字元中選取特定數量的字元
verify_code = random.sample(str_3, 6)
# 使用join方法拼接轉換為字串
verify_code = "".join(verify_code)
print(verify_code)
輸出:
Mk0L6Y

Process finished with exit code 0

25判斷閏年

year  = input("請輸入一個年份:")
year = int(year)
# 一行程式碼判斷年份是否是閏年
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
    print("{}是閏年!".format(year))
else:
    print("{}不是閏年!".format(year))
輸出示例:
請輸入一個年份:2000
2000是閏年!

Process finished with exit code 0

996 一直是網際網路老生常談的話題了,但拋開其他只談工作本身,你有沒有想過,下班晚、加班,有時候可能是因為自己工作比較低效?

所以,平時多積累好用、常用、簡潔的程式碼段真的非常有必要。

再次強調一下,如果覺得這些程式碼段有幫助,請一定要收藏起來,另外也不要忘了分享給你身邊的朋友和同事喲~

以上就是本次分享的所有內容,想要了解更多歡迎前往公眾號:Python 程式設計學習圈,每日干貨分享