Python Tricks and Tips(Continually updated)

最近在网上看到了一篇介绍python小技巧的英文文章,把它==翻译整理==到这里,方便以后自己查阅;同时,以后学习中遇到的一些python小技巧,我也会整理到这篇文章里。

原文地址:https://medium.com/better-programming/20-python-snippets-you-should-learn-today-8328e26ff124

记住一些python编程小技巧能够有助于我们的编码,同时也能节省一些搜索的时间。

Python Version: 3.5.2

  1. 反转字符串

通过切片操作实现字符串反转

1
2
3
4
5
6
7
8
9
# 通过切片操作实现字符串反转

my_string = "ABCDE"
reversed_string = my_string[::-1]

print(reversed_string)

# Output
# EDCBA

python中list的切片规则是[start, stop, step],那么[::-1]就是:我们从开始到结束遍历整个list,同时遍历步长step-1,遍历过程即为从位置[-1]遍历到位置[-length - 1],这样保存下来的list,就是原来字符串的逆序。

2.将字符串转换为标题格式(每个单词首字母大写)

调用title()方法即可

1
2
3
4
5
6
7
8
9
my_string = "my name is chaitanya baweja"

# 调用string类的title方法
new_string = my_string.title()

print(new_string)

# Output
# My Name Is Chaitanya Baweja

3.找到字符串中的唯一元素

我们可以利用以下的代码找到字符串中的唯一元素

1
2
3
4
5
6
7
8
9
10
11
my_string = "aavvccccddddeee"

# 将字符串转换为集合
temp_set = set(my_string)
# temp_set: {'a', 'v', 'c', 'd', 'e'}

# 使用join方法将集合拼接为字符串
new_string = ''.join(temp_set)

print(new_string)
# Output: avcde

python中的集合是一个无序的不重复元素序列,而join()方法可以将字符串序列拼接起来。

4.打印字符串或者列表n次

我们可以使用*n操作来打印字符串或列表n次,这种方法也能够用在初始化列表上。

1
2
3
4
5
6
7
8
9
10
n = 3 # 重复次数

my_string = "abcd"
my_list = [1, 2, 3]

print(my_string * n)
# abcdabcdabcd

print(my_string*n)
# [1, 2, 3, 1, 2, 3, 1, 2, 3]

初始化长度为n的列表:

1
new_list = [0] * n

5.对列表元素操作(列表解析-list comprehension)

我认为这是python中一项非常优雅的操作,通过一行代码,我们就可以基于原有列表或是其他数据创建一个新的列表。

例如下例中,通过将列表中每个元素乘2,创建一个新的列表

1
2
3
4
5
6
7
8
# 将列表中每个元素乘2

original_list = [1, 2, 3, 4]

new_list = [2 * x for x in original_list]

print(new_list)
# [2, 4, 6, 8]

我们可以在列表解析中加入判断

1
2
3
4
old_list = [1, 2, 3, 4]
new_list = [i**3 if i % 2 == 0 else i**2 for i in old_list]

print(new_list) # Output: [1, 8, 9, 64]

上述代码将原列表中的偶数立方、奇数平方,生成了新的列表。

我们可以在列表解析过程中加入多个循环

1
2
3
4
5
6
7
8
a = [1, 2, 3, 4]
b = [10, 11]

cart_prod = [(i, j) for i in a for j in b]
print cart_prod

# Output:
# [(1, 10), (1, 11), (2, 10), (2, 11), (3, 10), (3, 11), (4, 10), (4, 11)]

上述一行代码生成了ab两个列表间的笛卡尔积。

6.交换两个变量的值

相较于其他语言,python中变量值交换操作属实简单,对多个变量的赋值也很清晰:

1
2
3
4
5
6
7
# 为a,b赋值
a, b = 1, 2

a, b = b, a

print(a) # 2
print(b) # 1

7.切分字符串(string->list)

通过调用.split()方法实现对字符串的切分,通过传递参数,我们可以选择切分的分隔符:

1
2
3
4
5
6
7
8
9
10
string_1 = "My name is Chaitanya Baweja"
string_2 = "sample/ string 2"

# 默认按空格切分
print(string_1.split())
# ['My', 'name', 'is', 'Chaitanya', 'Baweja']

# 通过传递参数,按‘/’切分
print(string_2.split('/'))
# ['sample', ' string 2']

8.将字符串列表合并为字符串(list->string)

我们在3中介绍过使用join()拼接字符串:

1
2
3
4
5
6
7
8
9
10
11
12
13
list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja']

# 默认用空格拼接list
print(''.join(list_of_strings))

# Output
# My name is Chaitanya Baweja

# 用逗号拼接list
print(','.join(list_of_strings))

# Output
# My,name,is,Chaitanya,Baweja

9.判断字符串是否为回文串

我们已经介绍了反转字符串的方法,只需要判断反转后的字符串与原字符串是否相等即可:

1
2
3
4
5
6
7
8
9
my_string = "abcba"

if my_string == my_string[::-1]:
print("palindrome")
else:
print("not palindrome")

# Output
# palindrome

10.列表中的元素频率

统计列表中元素出现的频率有很多方法,我们可以使用字典,也可以使用Counter类。

Counter类能够记录容器中每个元素的频率,它返回一个字典,字典中的键值对为:{元素:元素出现次数}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# finding frequency of each element in a list
from collections import Counter

my_list = ['a', 'a', 'b', 'b', 'b', 'c', 'd', 'd', 'd', 'd', 'd']
count = Counter(my_list) # defining a counter object

print(count) # Of all elements
# Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})

print(count['b']) # of individual element
# 3

# 通过调用most_common()方法获取出现频率最高的元素
print(count.most_common(1))
# [('d', 5)]

11.判断两个字符串是否为同字母异构

这是Counter类的奇妙应用之一,可以来判断某个字符串是否是重新调换另一个字符串字符位置而成

1
2
3
4
5
6
7
8
9
from collections import Counter

str_1, str_2, str_3 = "acbde", "abced", "abcda"
cnt_1, cnt_2, cnt_3 = Counter(str_1), Counter(str_2), Counter(str_3)

if cnt_1 == cnt_2:
print('1 and 2 anagram')
if cnt_1 == cnt_3:
print('1 and 3 anagram')

12.try-except-else代码块

在python中,可以通过try-except代码块来处理异常。当没有异常发生时,我们可以通过增加一个else代码块来继续执行代码;或者通过增加一个finally代码块来忽略异常,继续执行:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
a, b = 1,0

try:
print(a/b)
# exception raised when b is 0
except ZeroDivisionError:
print("division by zero")
else:
print("no exceptions raised")
finally:
print("Run this always")
# Output
# division by zero
# Run this always

13.调用Enumerate方法获取下标与元素值

我们可以通过Enumerate方法在一次循环中同时获取元素下标与值:

1
2
3
4
5
6
7
8
9
10
my_list = ['a', 'b', 'c', 'd', 'e']

for index, value in enumerate(my_list):
print('{0}: {1}'.format(index, value))

# 0: a
# 1: b
# 2: c
# 3: d
# 4: e

14.查看对象的内存占用

1
2
3
4
5
6
7
8
import sys

num = 21

print(sys.getsizeof(num))

# In Python 2, 24
# In Python 3, 28

15.合并字典

1
2
3
4
5
6
7
8
dict_1 = {'apple': 9, 'banana': 6}
dict_2 = {'banana': 4, 'orange': 8}

combined_dict = {**dict_1, **dict_2}

print(combined_dict)
# Output
# {'apple': 9, 'banana': 4, 'orange': 8}

16.统计代码执行时间

1
2
3
4
5
6
7
8
9
10
11
import time

start_time = time.time()
# 开始执行
a, b = 1,2
c = a+ b
# 执行结束
end_time = time.time()
time_taken_in_micro = (end_time- start_time)*(10**6)

print(" Time taken in micro_seconds: {0} ms").format(time_taken_in_micro)

17.将高维数组转换为一维

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from iteration_utilities import deepflatten

# 深度为1的列表
def flatten(l):
return [item for sublist in l for item in sublist]

l = [[1,2,3],[3]]
print(flatten(l))
# [1, 2, 3, 3]

# 未知深度的列表
l = [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]]

print(list(deepflatten(l, depth=3)))
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

我们还可以使用Numpy库转换数组。

numpy.flatten(order='C')方法:默认参数为’C’,’C’表示按行顺序优先转换;’F’是指列顺序优先转换;’A’是指,若列表在内存中连续存储,则按列顺序优先转换;反之,则按行顺序优先转换;’K’是指按列表元素在内存出现的顺序转换。

1
2
3
4
5
a = np.array([[1,2], [3,4]])
a.flatten()
array([1, 2, 3, 4])
a.flatten('F')
array([1, 3, 2, 4])

18.从列表随机采样

1
2
3
4
5
6
7
8
import random

my_list = ['a', 'b', 'c', 'd', 'e']
num_samples = 2

samples = random.sample(my_list,num_samples)
print(samples)
# [ 'a', 'e'] this will have any 2 random values

还可以调用secrets库来生成随机样本:

1
2
3
4
5
6
7
8
9
10
import secrets                              
secure_random = secrets.SystemRandom()

my_list = ['a', 'b', 'c', 'd', 'e']
num_samples = 2

samples = secure_random.sample(my_list, num_samples)

print(samples)
# [ 'e', 'd'] this will have any 2 random values

19.integer->list

1
2
3
4
5
6
num = 123456

list_of_digits = list(map(int, str(num)))

print(list_of_digits)
# [1, 2, 3, 4, 5, 6]

20.判断列表是否存在重复元素

基于列表生成集合,通过判断列表长度与集合长度是否相等,即可判断列表是否存在重复元素。

1
2
3
4
5
6
7
8
9
10
11
def unique(l):
if len(l)==len(set(l)):
print("All elements are unique")
else:
print("List has duplicates")

unique([1,2,3,4])
# All elements are unique

unique([1,1,2,3])
# List has duplicates

21.自定义比较函数对列表排序

当我们想要用其他方式而不是数字大小顺序对列表排序时,我们可以通过cmp_to_key转换比较方式,下例中,我们将自定义函数传递给sorted()函数:

1
2
3
4
5
6
7
def custom_sort(nums) -> str:
def custom_cmp(a, b):
return a**2 - b**2

nums = sorted([num for num in nums], key=cmp_to_key(custom_cmp))

return nums

上述代码段能够按列表元素的平方大小进行排序。