10個Python編程小技巧

在這裏插入圖片描述

1. 變量交換

a = 1
b = 2
a, b = b, a # 實現了對兩個數的交換
a, b
(2, 1)

2. 字符串格式化

name = 'Jack'
country = 'China'
age = 18

# 1. 傳統的字符串拼接(很繁雜)
print("Hi, I'm " + name + ". I'm from " + country + ". And I'm " + str(age) + " years old.")

# 2. 百分號語法
print("Hi, I'm %s. I'm from %s. And I'm %d years old." %(name, country, age))

# 3. format函數
print("Hi, I'm {}. I'm from {}. And I'm {} years old.".format(name, country, age))
# print("Hi, I'm {0}. Yes, I'm {0}!".format(name, country, age)) # 索引0爲第一個參數

# 4. f-string寫法
print(f"Hi, I'm {name}. I'm from {country}. And I'm {age} years old.")
Hi, I'm Jack. I'm from China. And I'm 18 years old.
Hi, I'm Jack. I'm from China. And I'm 18 years old.
Hi, I'm Jack. I'm from China. And I'm 18 years old.
Hi, I'm Jack. I'm from China. And I'm 18 years old.

3. Yield 語法

# 傳統寫法
def fibo(n):
    a = 0
    b = 1
    nums = []
    for _ in range(n):
        nums.append(a)
        a, b = b, a+b
    return nums
for i in fibo(6):
    print(i)
0
1
1
2
3
5
# 用Yield函數
def fibo_y(n):
    a = 0
    b = 1
    for _ in range(n):
        yield a
        a, b = b, a+b
for i in fibo_y(6):
    print(i)
0
1
1
2
3
5

4. 列表解析式

# 傳統寫法
fruit = ['apple', 'pear', 'pineapple', 'orange', 'banana']
for i in range(len(fruit)):
    fruit[i] = fruit[i].upper()
fruit
['APPLE', 'PEAR', 'PINEAPPLE', 'ORANGE', 'BANANA']
# 簡潔寫法
fruits = ['apple', 'pear', 'pineapple', 'orange', 'banana']
fruits = [x.upper() for x in fruits]
fruits
['APPLE', 'PEAR', 'PINEAPPLE', 'ORANGE', 'BANANA']
# 挑選出以‘p’字母開頭的元素
fruits = ['apple', 'pear', 'pineapple', 'orange', 'banana']
filtered_fruits = [x for x in fruits if x.startswith('p')]
filtered_fruits
['pear', 'pineapple']

5. Enumerate函數

fruits = ['apple', 'pear', 'pineapple', 'orange', 'banana']
for i, x in enumerate(fruits):
    print(i, x)
0 apple
1 pear
2 pineapple
3 orange
4 banana

6.1 反向遍歷

fruits = ['apple', 'pear', 'pineapple', 'orange', 'banana']
for i, x in enumerate(reversed(fruits)):
    print(i, x)
0 banana
1 orange
2 pineapple
3 pear
4 apple

6.2 按順序遍歷

fruits = ['apple', 'pear', 'pineapple', 'orange', 'banana']
for i, x in enumerate(sorted(fruits)):
    print(i, x)
0 apple
1 banana
2 orange
3 pear
4 pineapple

7. 字典的合併操作

a = {'ross': '12', 'xiaoming': '23'}
b = {'lilei': '34', 'zhangsan': '45'}
c = {**a, **b}
c
{'ross': '12', 'xiaoming': '23', 'lilei': '34', 'zhangsan': '45'}

8. 三元運算符

score = [56, 63, 80, 20, 100]
s = ['pass' if x>60 else 'fail' for x in score]
s
['fail', 'pass', 'pass', 'fail', 'pass']

9. 序列解包

name = 'Jack Tim'
first_name, last_name = name.split()
first_name, last_name
('Jack', 'Tim')

10. with語句

# 傳統寫法
f = open('haha.txt', 'r')
s = f.read()
f.close() # 不可省略,會佔用資源
# with語句
with open('haha.txt', 'r') as f:
    s = f.read()

參考內容

https://www.bilibili.com/video/BV1kT4y1u72i?from=search&seid=12924391744156658505

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章