2024年11月11日 星期一

Python 單行程式碼30例

 Python 單行程式碼30例

1. 列表生成 (List Comprehension)

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

2. 反轉字串

reversed_string = "Hello World"[::-1]

3. 快速生成字典

squared_dict = {x: x**2 for x in range(5)}

4. 合併並排序兩個列表

merged_sorted_list = sorted([3, 1, 4] + [2, 8, 5])

5. 計算列表中數字總和

total = sum([1, 2, 3, 4, 5])

6. 找出列表中的最大值

max_value = max([10, 20, 30, 40])

7. 過濾偶數

evens = [x for x in range(10) if x % 2 == 0]

8. 檢查字串是否為回文

is_palindrome = lambda s: s == s[::-1]

9. 一行寫入文件

open("file.txt", "w").write("Hello, World!")

10. 計算文件中的單詞數量

word_count = len(open("file.txt").read().split())

這些範例展示了 Python 簡潔高效的語法,適合日常快速實現小工具或概念驗證!

以下是另外 10 個 Python 單行程式碼範例:

11. 生成費氏數列

fibonacci = [0, 1] + [sum(fibonacci[-2:]) for _ in range(8)]

12. 打亂列表

import random; shuffled = random.sample([1, 2, 3, 4, 5], len([1, 2, 3, 4, 5]))

13. 計算文字的字元頻率

from collections import Counter; char_freq = Counter("hello world")

14. 扁平化嵌套列表

flattened = [item for sublist in [[1, 2], [3, 4], [5]] for item in sublist]

15. 計算兩個列表的交集

intersection = list(set([1, 2, 3]) & set([2, 3, 4]))

16. 轉置矩陣

matrix = [[1, 2, 3], [4, 5, 6]]; transposed = list(zip(*matrix))

17. 找出列表中第二大的數字

second_largest = sorted(set([10, 20, 20, 30, 40]))[-2]

18. 判斷所有數字是否為偶數

all_even = all(x % 2 == 0 for x in [2, 4, 6])

19. 計算列表中數字的平方根

import math; sqrt_list = [math.sqrt(x) for x in [4, 9, 16]]

20. 合併多個字典

merged_dict = {**{"a": 1}, **{"b": 2}, **{"c": 3}}

21. 生成 1 到 100 的隨機數列表

import random; random_numbers = [random.randint(1, 100) for _ in range(10)]

22. 檢查數字是否為質數

is_prime = lambda n: n > 1 and all(n % i != 0 for i in range(2, int(n**0.5) + 1))

23. 生成指定長度的隨機字串

import random, string; random_string = ''.join(random.choices(string.ascii_letters + string.digits, k=10))

24. 找出列表中的重複項目

duplicates = [x for x in set([1, 2, 2, 3, 3, 4]) if [1, 2, 2, 3, 3, 4].count(x) > 1]

25. 計算兩個日期之間的天數

from datetime import date; days_diff = (date(2024, 11, 10) - date(2024, 11, 1)).days

26. 將列表中所有數字的類型轉換為字串

stringified = list(map(str, [1, 2, 3, 4]))

27. 快速讀取文件的所有行

lines = [line.strip() for line in open("file.txt").readlines()]

28. 找出字串中所有出現的子字串位置

positions = [i for i in range(len("hello world")) if "hello world".startswith("l", i)]

29. 合併多個列表並去除重複項

merged_unique = list(set([1, 2, 3] + [3, 4, 5] + [5, 6, 7]))

30. 創建一個指定大小的零矩陣

zero_matrix = [[0]*3 for _ in range(3)]

沒有留言:

張貼留言