【速度收藏】20个常用的Python技巧,太赞啦

75 篇文章 0 订阅
43 篇文章 0 订阅

Python的可读性和简单性是其广受欢迎的两大原因,本文介绍20个常用的Python技巧来提高代码的可读性,并能帮助你节省大量时间,下面的技巧将在你的日常编码练习中非常实用。

1.字符串反转

使用Python切片反转字符串:

\# 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. 字符串查找唯一元素

使用集合的概念查找字符串的唯一元素:

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)  
  
\# output  
\# cdvae

4.重复打印字符串和列表n次

你可以使用乘法符号(*)打印字符串或列表多次:

n \= 3 \# number of repetitions  
  
my\_string \= "abcd"  
my\_list \= \[1,2,3\]  
  
print(my\_string\*n)  
\# abcdabcdabcd  
  
print(my\_list\*n)  
\# \[1,2,3,1,2,3,1,2,3\]

5.列表生成

\# Multiplying each element in a list by 2  
  
original\_list \= \[1,2,3,4\]  
  
new\_list \= \[2\*x for x in original\_list\]  
  
print(new\_list)  
\# \[2,4,6,8\]

6.变量交换

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"  
  
\# default separator ' '  
print(string\_1.split())  
\# \['My', 'name', 'is', 'Chaitanya', 'Baweja'\]  
  
\# defining separator as '/'  
print(string\_2.split('/'))  
\# \['sample', ' string 2'\]

8.多个字符串组合为一个字符串

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. 统计列表中元素的次数

\# 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类判断两个字符串是否为Anagrams。

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')  
  
\# output  
\# 1 and 2 anagram

12. 使用try-except-else-block模块

except获取异常处理:

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. 使用枚举函数得到key/value对

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.检查对象的内存使用情况

import sys  
  
num \= 21  
  
print(sys.getsizeof(num))  
  
\# In Python 2, 24  
\# In Python 3, 28

15.合并字典

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  
for i in range(10\*\*5):  
    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)  
  
\# output  
\# 18770.217895507812

17. 列表展开

from iteration\_utilities import deepflatten  
  
\# if you only have one depth nested\_list, use this  
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\]  
  
\# if you don't know how deep the list is nested  
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\]

18. 列表采样

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

19.数字化

将整数转化成数字列表:

num \= 123456  
  
\# using map  
list\_of\_digits \= list(map(int, str(num)))  
  
print(list\_of\_digits)  
\# \[1, 2, 3, 4, 5, 6\]  
  
\# using list comprehension  
list\_of\_digits \= \[int(x) for x in 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

最后这里免费分享给大家一份Python全套学习资料,包含视频、源码。课件,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以加我微信一起来学习交流。

Python所有方向的学习路线图,清楚各个方向要学什么东西

100多节Python课程视频,涵盖必备基础、爬虫和数据分析

100多个Python实战案例,学习不再是只会理论

华为出品独家Python漫画教程,手机也能学习

历年互联网企业Python面试真题,复习时非常方便

上述这份完整版的Python全套学习资料已经上传CSDN官方,朋友们如果需要可以直接划到文末免费领取【保证100%免费

一、Python所有方向的学习路线

Python所有方向路线就是把Python常用的技术点做整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

二、学习软件

工欲善其事必先利其器。学习Python常用的开发软件都在这里了,给大家节省了很多时间。

三、全套PDF电子书

书籍的好处就在于权威和体系健全,刚开始学习的时候你可以只看视频或者听某个人讲课,但等你学完之后,你觉得你掌握了,这时候建议还是得去看一下书籍,看权威技术书籍也是每个程序员必经之路。

在这里插入图片描述

四、入门学习视频

我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了。

四、实战案例

光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。

五、清华编程大佬出品《漫画看学Python》

用通俗易懂的漫画,来教你学习Python,让你更容易记住,并且不会枯燥乏味。

在这里插入图片描述
配套学习视频:
在这里插入图片描述

六、面试资料

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。


这份完整版的Python全套学习资料已经上传CSDN官方,朋友们如果需要可以点击下方CSDN官方认证微信名片免费领取↓↓↓【保证100%免费

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值