20个常用的Python小技巧

 

2019 年第 73 篇文章,总第 97 篇文章

原题 | 20 Python Snippets You Should Learn Today

作者 | Chaitanya Baweja

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

译者 | kbsc13("算法猿的成长"公众号作者)

声明 | 翻译是出于交流学习的目的,欢迎转载,但请保留本文出于,请勿用作商业或者非法用途

Python 是一门可读性和简洁性都非常好的编程语言,经常可以用简单的一行代码即实现其他语言需要多行代码才可以实现的功能。今天会介绍 20 个非常有用的小技巧。

今日推荐文章

github标星8331+:吴恩达深度学习课程资源(完整笔记、中英文字幕视频、python作业,提供百度云镜像!)!)


1. 反转字符串

采用切片操作实现字符串的反转:

# Reversing a string using slicing

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

print(reversed_string)

# Output
# EDCBA

2. 实现首字母大写

这个小技巧是让字符串中每个单词的首字母变为大写,通过方法 title() 实现:

my_string = "my name is chaitanya baweja"

# using the title() function of string class
new_string = my_string.title()

print(new_string)

# Output
# My Name Is Chaitanya Baweja

3. 查找字符串中唯一元素

这个技巧是查找字符串中不重复的元素有哪些,通过集合 set 来实现:

my_string = "aavvccccddddeee"

# converting the string to a set
temp_set = set(my_string)

# stitching set into a string using join
new_string = ''.join(temp_set)

print(new_string)

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

这个技巧通过乘法即可实现打印多次的操作:

n = 3 # number of repetitions

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 个重复的常数元素的列表,如下所示:

n = 4
my_list = [0]*n 
# [0, 0, 0, 0]

5. 列表推导式

列表推导式是一种非常优雅的基于其他列表来创建新列表的方法,示例如下所示:

original_list = [1,2,3,4]

new_list = [2*x for x in original_list]

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

6. 交换两个变量

Python 中交换两个变量的数值是非常简单的,完全不需要第三个变量作为中间值。示例如下所示:

a = 1
b = 2

a, b = b, a

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

7. 字符串分割为一串子字符串列表

采用 split() 方法可以将字符串分割为一个包含其子字符串的列表,示例如下所示:

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. 合并多个字符串为一个字符串

采用 join() 方法可以将多个字符串合并为一个字符串。这相当于上一条技巧的反向操作。示例如下所示:

list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja']

# Using join with the comma separator
print(','.join(list_of_strings))

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

9. 判断字符串是否回文

通过反转字符串,再和原字符串比较,可以判断是否为回文,示例如下:

my_string = "abcba"

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

# Output
# palindrome

10. 统计列表元素的个数

有多种方式可以实现这个技巧,但我最喜欢的是采用 Counter 类。

Counter 可以统计给定列表中每个元素的个数,返回一个字典格式。示例如下,其中most_common()方法可以返回列表中数量最多的元素

# 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

print(count.most_common(1)) # most frequent element
# [('d', 5)]

11. 判断两个字符串是否是字谜(Anagrams)

字谜(Anagrams)是指将一个单词打乱其字母顺序,重新排列为一个新的单词。

Counter正好可以用于解决这个问题,因为如果两个字符串的 Counter 对象相等,就表示它们就是字谜,因为包含相同元素且元素数量都相同。

示例如下:

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 语句会更加有帮助,它是在没有发生异常时,执行完 try 语句后运行的语句。

此外,如果需要运行是否发现异常的都需要执行的代码,可以采用 finally ,示例如下:

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")

13. 采用 Enumerate 来获取索引值

在迭代列表的时候,可以采用 enumerate 来得到索引值,示例如下:

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

注意,这里还可以指定索引开始的范围,只需要在调用 enumerate() 时候,添加一个参数,如下所示:

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

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

14. 检查一个对象的内存使用量

可以采用 sys.getsizeof() 检查,示例如下:

import sys

num = 21

print(sys.getsizeof(num))

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

更详细内容可以查看 https://code.tutsplus.com/tutorials/understand-how-much-memory-your-python-objects-use--cms-25609

15. 合并两个字典

在 Python2 版本的时候可以采用 update() 方法实现合并字典的操作,但在 Python3.5 后的版本,可以采用新的方式实现,操作更加简单,如下所示:

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. 计算代码执行时间

采用 time 模块来计算一段代码的执行时间,例子如下:

import time

start_time = time.time()
# Code to check follows
a, b = 1,2
c = a+ b
# Code to check ends
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. 展平元素为列表的列表

有时候并确定一个列表中的深度有多深,所以你只想简单的将所有元素都放在一个列表中,实现技巧代码如下所示:

from iteration_utilities import deepflatten

# 列表只有一层深度的情况,采用这个函数
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 方式,参考文章 https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.htmlhttps://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html

18. 从列表中采样

采用 random 模块可以对一个列表随机采样 n 个元素,示例如下所示:

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

另外,在 Python 3 中推荐采用 secrets 模块,基于密码学的目的来随机生成样本,示例如下:

import secrets                              # imports secure module.
secure_random = secrets.SystemRandom()      # creates a secure random object.

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. 数字化

下面是一个例子,将一个数字转换为一个数字列表的形式:

num = 123456

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

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

20. 检查唯一性

下面的代码是用于判断一个列表的所有元素是否都是唯一没有重复的:

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

小结

以上介绍的都是比较常用的小技巧,代码函数不多,非常简洁易懂。

这里也推荐一个网站--30secondsofcode,可以更好搜索这些常用的技巧:

https://python.30secondsofcode.org/

欢迎关注我的微信公众号--算法猿的成长,或者扫描下方的二维码,大家一起交流,学习和进步!

640?wx_fmt=png

 

ps:以后每次接广告后,第二天或者当天的次条都会有一个抽奖活动,金额不定,这需要视能得到多少广告费了u1F602.png,所以希望大家可以多多支持,多多点击阅读,觉得不错的帮忙点下在看或者转发分享,谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

spearhead_cai

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

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

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

打赏作者

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

抵扣说明:

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

余额充值