Python的可读性和简单性是其广受欢迎的两大原因,本文介绍20个常用的Python技巧来提高代码的可读性,并能帮助你节省大量时间,下面的技巧将在你的日常编码练习中非常实用。
使用Python切片反转字符串:
\# Reversing a string using slicing
my\_string \= "ABCDE"
reversed\_string \= my\_string\[::\-1\]
print(reversed\_string)
\# Output
\# EDCBA
使用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
使用集合的概念查找字符串的唯一元素:
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
你可以使用乘法符号(*)打印字符串或列表多次:
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\]
\# 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
使用.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'\]
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
my\_string \= "abcba"
if my\_string \== my\_string\[::\-1\]:
print("palindrome")
else:
print("not palindrome")
\# Output
\# palindrome
\# 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)\]
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
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
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
import sys
num \= 21
print(sys.getsizeof(num))
\# In Python 2, 24
\# In Python 3, 28
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}
使用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
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\]
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
将整数转化成数字列表:
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\]
检查列表中每个元素是否为唯一的:
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面试真题
,复习时非常方便
保证100%免费
】Python所有方向路线就是把Python常用的技术点做整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。
工欲善其事必先利其器。学习Python常用的开发软件都在这里了,给大家节省了很多时间。
书籍的好处就在于权威和体系健全,刚开始学习的时候你可以只看视频或者听某个人讲课,但等你学完之后,你觉得你掌握了,这时候建议还是得去看一下书籍,看权威技术书籍也是每个程序员必经之路。
我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了。
光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。
用通俗易懂的漫画,来教你学习Python,让你更容易记住,并且不会枯燥乏味。
我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。
保证100%免费
】