商场网站建设模板,梵客官网,wordpress手机端下滑刷新,wordpress文章加密搜索不到Python 是一个解释型语言#xff0c;可读性与易用性让它越来越热门。
正如 Python 之禅中所述#xff1a;
优美胜于丑陋#xff0c;明了胜于晦涩。
在你的日常编码中#xff0c;以下技巧可以给你带来意想不到的收获。
1、字符串反转
下面的代码片段#xff0c;使用 P…Python 是一个解释型语言可读性与易用性让它越来越热门。
正如 Python 之禅中所述
优美胜于丑陋明了胜于晦涩。
在你的日常编码中以下技巧可以给你带来意想不到的收获。
1、字符串反转
下面的代码片段使用 Python 中 slicing 操作来实现字符串反转
# Reversing a string using slicingmy_string ABCDE
reversed_string my_string[::-1]print(reversed_string)# Output
# EDCBA2、首字母大写
下面的代码片段可以将字符串进行首字母大写使用的是 String 类的 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 Baweja3、取组成字符串的元素
下面的代码片段可以用来找出一个字符串中所有组成他的元素我们使用的是 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)# Output
# acedv4、重复输出String/List
可以对 String/List 进行乘法运算这个方法可以使用它们任意倍增。
n 3 # number of repetitions
my_string abcd
my_list [1,2,3]print(my_string*n)
# abcdabcdabcdprint(my_string*n)
# [1,2,3,1,2,3,1,2,3]有一个很有意思的用法定义包含n个常量的列表
n 4
my_list [0]*n # n 表示所需列表的长度
# [0, 0, 0, 0]5、列表推导式
列表推导式提供了一种更优雅的方式处理列表。以下代码片段中将旧列表中的元素乘以2来创建新的列表
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 2a, b b, aprint(a) # 2
print(b) # 17、字符串拆分
使用 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、字符串拼接
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,Baweja9、回文检测
在前面我们已经说过了如何翻转一个字符串所以回文检测非常的简单
my_string abcbaif my_string my_string[::-1]:print(palindrome)
else:print(not palindrome)# Output
# palindrome10、元素重复次数
在Python中有很多方法可以做这件事情但是我最喜欢的还是 Counter 这个类。Counter会计算每一个元素出现的次数Counter()会返回一个字典元素作为key出现的次数作为 value。我们也可以使用 most_common() 这个方法来获取出现字数最多的元素。
from 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)]11、变位词使用
Counter的一个很有意思的用法是找变位词变位词一种把某个词或句子的字母的位置顺序加以改换所形成的新词。使用 Counter 得到的两个对象如果相等则他们是变位词
from collections import Counterstr_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 可用于当没有异常发生时执行。如果你需要执行一些代码不管是否发生过异常请使用 final
a, b 1,0try: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、枚举遍历
下面的代码片段中遍历列表中的值和对应的索引
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: e14、对象使用内存大小
下面的代码片段展示了如何获取一个对象所占用的内存大小
import sysnum 21print(sys.getsizeof(num))# In Python 2, 24
# In Python 3, 2815、合并两个字典
在 Python 2 中使用 update() 方法来合并在 Python 3.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 timestart_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# 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 dont know how deep the list is nested
l [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]]print(list(deepflatten(l, depth3)))
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]Numpy flatten 可以更好的处理你格式化好的数据。
18、随机取样
下面的例子中使用 random 库实现了从列表中随机取样。
import randommy_list [a, b, c, d, e]
num_samples 2samples random.sample(my_list,num_samples)
print(samples)随机取样我推荐使用 secrets 库来实现更安全。下面的代码片段只能在 Python 3 中运行
##学习中遇到问题没人解答小编创建了一个Python学习交流群309488165
import secrets # imports secure module.
secure_random secrets.SystemRandom() # creates a secure random object.my_list [a,b,c,d,e]
num_samples 2samples secure_random.sample(my_list, num_samples)print(samples)19、数字化
下面代码将一个整形数转成一个数字化的对象
num 123456list_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 uniqueunique([1,1,2,3])
# List has duplicates