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
题外话
“不是只有程序员才要学编程?!”
认真查了一下招聘网站,发现它其实早已变成一项全民的基本技能了。
连国企都纷纷要求大家学Python!
世界飞速发展,互联网、大数据冲击着一切,各行各业对数据分析能力的要求越来越高,这便是工资差距的原因,学习编程顺应了时代的潮流。
在这个大数据时代,从来没有哪一种语言可以像Python一样,在自动化办公、爬虫、数据分析等领域都有众多应用。
更没有哪一种语言,语法如此简洁易读,消除了普通人对于“编程”这一行为的恐惧,从小学生到老奶奶都可以学会。
《2020年职场学习趋势报告》显示,在2020年最受欢迎的技能排行榜,Python排在第一。
它的角色类似于现在Office,成了进入职场的第一项必备技能。
如果你也想增强自己的竞争力,分一笔时代的红利,我的建议是,少加点班,把时间腾出来,去学一学Python。
因为,被誉为“未来十年的职场红利”的Python,赚钱、省钱、找工作、升职加薪简直无所不能!
目前,Python人才需求增速高达**174%,人才缺口高达50万,**部分领域如人工智能、大数据开发, 年薪30万都招不到人!
感兴趣的小伙伴,赠送全套Python学习资料,包含面试题、简历资料等具体看下方。
👉CSDN大礼包🎁:全网最全《Python学习资料》免费赠送🆓!(安全链接,放心点击)
![](https://hnxx.oss-cn-shanghai.aliyuncs.com/official/1689929181288.gif)
一、Python所有方向的学习路线
Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照下面的知识点去找对应的学习资源,保证自己学得较为全面。
二、Python必备开发工具
工具都帮大家整理好了,安装就可直接上手!
三、最新Python学习笔记
当我学到一定基础,有自己的理解能力的时候,会去阅读一些前辈整理的书籍或者手写的笔记资料,这些笔记详细记载了他们对一些技术点的理解,这些理解是比较独到,可以学到不一样的思路。
四、Python视频合集
观看全面零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。
五、实战案例
纸上得来终觉浅,要学会跟着视频一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。
六、面试宝典
简历模板![在这里插入图片描述](https://img-blog.csdnimg.cn/646863996ac44da8af500c049bb72fbd.png#pic_center)
![](https://hnxx.oss-cn-shanghai.aliyuncs.com/official/1689929181288.gif)