摘要:Python的可读性和简单性是其广受欢迎的两大原因,本文介绍20个常用的Python技巧来提高代码的可读性,并能帮助你节省大量时间,下面的技巧将在你的日常编码练习中非常实用。
Python的可读性和简单性是其广受欢迎的两大原因,本文介绍20个常用的Python技巧来提高代码的可读性,并能帮助你节省大量时间,下面的技巧将在你的日常编码练习中非常实用。
字符串反转
使用Python切片反转字符串:
# Reversing a string using slicingreversed_string = my_string[::-1]# Output# EDCBA每个单词的第一个字母大写
my_string = "my name is chaitanya baweja"# using the title function of string classnew_string = my_string.titleprint(new_string)# Output# My Name Is Chaitanya Baweja重复打印字符串和列表n次
你可以使用乘法符号(*)打印字符串或列表多次:
列表生成
# Multiplying each element in a list by 2original_list = [1,2,3,4]多个字符串组合为一个字符串
list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja']# Using join with the comma separatorprint(','.join(list_of_strings))# Output# My,name,is,Chaitanya,Baweja检测字符串是否为回文
# Output# palindrome统计列表中元素的次数
# finding frequency of each element in a listfrom collections import Countermy_list = ['a','a','b','b','b','c','d','d','d','d','d']count = Counter(my_list) # defining a counter objectprint(count) # Of all elements# Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})print(count['b']) # of individual element# 3print(count.most_common(1)) # most frequent element# [('d', 5)]Anagrams的含义为两个单词中,每个英文单词(不含大小写)出现的次数相同,使用Counter类判断两个字符串是否为Anagrams。
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:# output# 1 and 2 anagram使用枚举函数得到key/value对
my_list = ['a', 'b', 'c', 'd', 'e']检查对象的内存使用情况
import sysnum = 21print(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}开启职业新征程
职业规划帮你掌握人生航向
了解自己的优势,找到适合自己的岗位!
人生不只有一条路,
职业规划帮你发现更多可能性!
赶快来了解一下吧
👇👇👇
仅需9.9元
让爱数据助力你的职场生涯
来源:妤婕教育分享