Python编程的50个小技巧

Python是一种广泛应用于各种领域的强大编程语言,其简洁的语法和丰富的库使得编程更加高效和愉快。本文将介绍50个Python编程的小技巧,每个技巧都附有代码案例和解释,帮助你更高效地编写Python代码。

文章目录

1. 交换两个变量的值

Python提供了一种简洁的方法来交换两个变量的值,而无需借助第三个变量。

a, b = 1, 2
a, b = b, a
print(a, b)  # 输出: 2 1

2. 列表推导式

列表推导式可以用简洁的语法创建列表。

squares = [x**2 for x in range(10)]
print(squares)  # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

3. 使用enumerate获取索引和值

enumerate函数可以同时获取列表的索引和值。

list1 = ['a', 'b', 'c']
for index, value in enumerate(list1):
    print(index, value)

4. 使用zip函数并行迭代多个序列

zip函数可以将多个可迭代对象打包在一起,并行迭代。

names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 88]
for name, score in zip(names, scores):
    print(f"{name}: {score}")

5. 使用*操作符解包列表/元组

*操作符可以将列表或元组的元素解包成单独的元素。

numbers = [1, 2, 3, 4]
print(*numbers)  # 输出: 1 2 3 4

6. 合并多个字典

可以使用**操作符将多个字典合并成一个字典。

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict)  # 输出: {'a': 1, 'b': 3, 'c': 4}

7. 使用collections.Counter统计元素频率

Counter是一个集合类,用于计数可哈希对象。

from collections import Counter
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
word_count = Counter(words)
print(word_count)  # 输出: Counter({'apple': 3, 'banana': 2, 'orange': 1})

8. 反转字符串

通过切片操作可以反转字符串。

s = "hello"
reversed_s = s[::-1]
print(reversed_s)  # 输出: "olleh"

9. 列表的浅拷贝和深拷贝

浅拷贝和深拷贝的区别在于浅拷贝只复制对象的引用,而深拷贝复制对象及其引用对象的副本。

import copy
original = [[1, 2, 3], [4, 5, 6]]
shallow_copy = original.copy()
deep_copy = copy.deepcopy(original)

10. 使用itertools生成所有排列组合

itertools模块提供了生成排列和组合的工具。

import itertools
perms = list(itertools.permutations([1, 2, 3]))
print(perms)  # 输出: 所有排列

11. 简单的HTTP请求

使用requests库可以轻松进行HTTP请求。

import requests
response = requests.get('https://api.github.com')
print(response.json())

12. 使用f-strings格式化字符串

f-strings是一种格式化字符串的简洁方式。

name = "Alice"
age = 30
print(f"{name} is {age} years old.")  # 输出: Alice is 30 years old.

13. 计算列表中的最大值和最小值

Python内置的maxmin函数可以直接用于计算列表的最大值和最小值。

numbers = [1, 2, 3, 4, 5]
print(max(numbers))  # 输出: 5
print(min(numbers))  # 输出: 1

14. 列表切片

列表切片可以用来获取列表的子集。

numbers = [1, 2, 3, 4, 5]
print(numbers[1:3])  # 输出: [2, 3]
print(numbers[:3])   # 输出: [1, 2, 3]
print(numbers[3:])   # 输出: [4, 5]

15. 字符串分割和连接

可以使用splitjoin方法分割和连接字符串。

s = "apple,banana,orange"
fruits = s.split(',')
print(fruits)  # 输出: ['apple', 'banana', 'orange']
new_s = ','.join(fruits)
print(new_s)  # 输出: "apple,banana,orange"

16. 使用defaultdict处理缺失键

defaultdict可以避免键不存在时抛出KeyError异常。

from collections import defaultdict
dd = defaultdict(int)
dd['a'] += 1
print(dd)  # 输出: defaultdict(<class 'int'>, {'a': 1})

17. 查找列表中元素的索引

可以使用index方法查找元素在列表中的索引。

numbers = [1, 2, 3, 4, 5]
print(numbers.index(3))  # 输出: 2

18. 检查对象类型

使用isinstance可以检查对象是否是某个特定的类型。

print(isinstance(5, int))  # 输出: True
print(isinstance('hello', str))  # 输出: True

19. 使用生成器节省内存

生成器在需要时才生成值,因此非常节省内存。

def generate_numbers():
    for i in range(10):
        yield i

gen = generate_numbers()
print(next(gen))  # 输出: 0
print(next(gen))  # 输出: 1

20. 使用allany进行逻辑判断

allany函数用于检查所有或任意条件是否满足。

numbers = [2, 4, 6, 8]
print(all(n % 2 == 0 for n in numbers))  # 输出: True
print(any(n % 2 != 0 for n in numbers))  # 输出: False

21. 列表展平

使用列表推导式展平嵌套列表。

nested_list = [[1, 2, 3], [4, 5, 6]]
flat_list = [item for sublist in nested_list for item in sublist]
print(flat_list)  # 输出: [1, 2, 3, 4, 5, 6]

22. 字符串转换为日期

使用datetime模块将字符串转换为日期对象。

from datetime import datetime
date_str = '2023-05-19'
date_obj = datetime.strptime(date_str, '%Y-%m-%d')
print(date_obj)  # 输出: 2023-05-19 00:00:00

23. 获取当前日期和时间

datetime模块可以获取当前日期和时间。

from datetime import datetime
now = datetime.now()
print(now)  # 输出: 当前日期和时间

24. 获取文件大小

使用os.path模块可以获取文件的大小。

import os
file_size = os.path.getsize('example.txt')
print(file_size)  # 输出: 文件大小(字节)

25. 检查文件或目录是否存在

使用os.path模块可以检查文件或目录是否存在。

import os
print(os.path.exists('example.txt'))  # 输出: True 或 False

26. 使用glob模块查找文件

glob模块可以查找符合特定模式的文件。

import glob
files = glob.glob('*.txt')
print(files)  # 输出: 匹配的文件列表

27. 使用namedtuple创建具名元组

namedtuple可以创建具有字段名的元组。

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p

.x, p.y)  # 输出: 1 2

28. 合并多个字符串

使用+操作符或join方法可以合并多个字符串。

str1 = "Hello"
str2 = "World"
combined = str1 + ' ' + str2
print(combined)  # 输出: Hello World

combined = ' '.join([str1, str2])
print(combined)  # 输出: Hello World

29. 查找子字符串

可以使用in运算符或find方法查找子字符串。

s = "Hello World"
print('World' in s)  # 输出: True
print(s.find('World'))  # 输出: 6

30. 字符串替换

使用replace方法可以替换字符串中的子字符串。

s = "Hello World"
new_s = s.replace('World', 'Python')
print(new_s)  # 输出: Hello Python

31. 检查字符串是否为数字

可以使用isdigit方法检查字符串是否只包含数字。

s = "12345"
print(s.isdigit())  # 输出: True

32. 生成随机数

使用random模块生成随机数。

import random
print(random.randint(1, 10))  # 输出: 1到10之间的随机整数

33. 打乱列表

使用random.shuffle打乱列表顺序。

import random
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)  # 输出: 打乱后的列表

34. 统计列表中元素的个数

使用len函数统计列表中元素的个数。

numbers = [1, 2, 3, 4, 5]
print(len(numbers))  # 输出: 5

35. 将列表转换为集合

使用set函数将列表转换为集合,从而删除重复元素。

numbers = [1, 2, 3, 1, 2, 3]
unique_numbers = set(numbers)
print(unique_numbers)  # 输出: {1, 2, 3}

36. 使用try...except处理异常

使用try...except块可以捕获和处理异常。

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

37. 读取文件内容

使用open函数读取文件内容。

with open('example.txt', 'r') as file:
    content = file.read()
print(content)

38. 写入文件

使用open函数写入文件内容。

with open('example.txt', 'w') as file:
    file.write('Hello, World!')

39. 追加文件内容

使用open函数追加文件内容。

with open('example.txt', 'a') as file:
    file.write('\nAppend this line.')

40. 使用json模块解析JSON数据

json模块可以解析和生成JSON数据。

import json
json_str = '{"name": "Alice", "age": 30}'
data = json.loads(json_str)
print(data)  # 输出: {'name': 'Alice', 'age': 30}

json_data = json.dumps(data)
print(json_data)  # 输出: '{"name": "Alice", "age": 30}'

41. 使用csv模块读取CSV文件

csv模块可以读取和写入CSV文件。

import csv
with open('example.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

42. 使用csv模块写入CSV文件

import csv
with open('example.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['name', 'age'])
    writer.writerow(['Alice', 30])

43. 获取列表的最后一个元素

使用索引-1可以获取列表的最后一个元素。

numbers = [1, 2, 3, 4, 5]
print(numbers[-1])  # 输出: 5

44. 计算字符串的长度

使用len函数可以计算字符串的长度。

s = "Hello, World!"
print(len(s))  # 输出: 13

45. 检查列表是否为空

通过检查列表的长度可以确定列表是否为空。

numbers = []
print(len(numbers) == 0)  # 输出: True
print(not numbers)  # 输出: True

46. 获取字典的所有键

使用keys方法可以获取字典的所有键。

d = {'a': 1, 'b': 2, 'c': 3}
print(d.keys())  # 输出: dict_keys(['a', 'b', 'c'])

47. 获取字典的所有值

使用values方法可以获取字典的所有值。

d = {'a': 1, 'b': 2, 'c': 3}
print(d.values())  # 输出: dict_values([1, 2, 3])

48. 获取字典的所有键值对

使用items方法可以获取字典的所有键值对。

d = {'a': 1, 'b': 2, 'c': 3}
print(d.items())  # 输出: dict_items([('a', 1), ('b', 2), ('c', 3)])

49. 字典键值对的遍历

可以使用items方法遍历字典的键值对。

d = {'a': 1, 'b': 2, 'c': 3}
for key, value in d.items():
    print(key, value)

50. 使用lambda创建匿名函数

lambda关键字可以创建简单的匿名函数。

add = lambda x, y: x + y
print(add(2, 3))  # 输出: 5
  • 14
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

袁袁袁袁满

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值