30个Python实用代码片段

2023-02-19 0 603

1.检查和多次重复原素上面的方式能检查和取值条目中与否有多次重复的原素。它采用了 set()特性,该特性Sonbhadra从条目中删掉多次重复的原素。

def allunique(lst):return len(lst)== len(set(lst))

x =[1,1,2,2,3,2,3,4,5,6]y =[1,2,3,4,5]allunique(x)# Falseallunique(y)# True

2.不定式词检验三个数组与否相辅相成不定式词(即相互倒转字符串次序)

from collections import Counter

def anagram(first, second):return Counter(first)== Counter(second)anagram(“abcd3″,”3acdb”)# True

3.检查和缓存采用情形下列程序标识符需用来检查和第一类的缓存采用情形。

import sysvariable =30print(sys.getsizeof(variable))# 24

4.二进制大小不一排序下列方式将以二进制为基层单位回到数组宽度。

def bytesize(string):return(len(string.encode(utf-8)))

bytesize(1234)# 4bytesize(Hello World)# 11

5.多次重复列印数组 N 次下列标识符不须要采用循环式方可列印某一数组 n 次

n =2;s =”Programming”; print(s * n);# ProgrammingProgramming

6.第一个字母小写下列程序标识符采用 title()方式将数组内的每一词展开第一个字母小写。

s =”programming is awesome”print(s.title())# Programming Is Awesome

7.分块下列方式采用 range()将条目分块为指定大小不一的较小条目。

from math import ceil

def chunk(lst, size):return list(map(lambda x: lst[x * size:x * size + size],list(range(0, ceil(len(lst)/ size)))))chunk([1,2,3,4,5],2)# [[1,2],[3,4],5]

8.压缩下列方式采用 fliter()删掉条目中的错误值(如:False, None,0 和“”)

def compact(lst):return list(filter(bool, lst))compact([0,1, False,2,,3,a,s,34])# [1,2,3,a,s,34]

9.间隔数下列程序标识符能用来转换一个二维数组。

array =[[a,b],[c,d],[e,f]]transposed = zip(*array)print(transposed)# [(a,c,e),(b,d,f)]

10.链式比较下列标识符能在一行中用各种操作符展开多次比较。

a =3print(2 < a <8)# Trueprint(1== a <2)# False

11.逗号分隔下列程序标识符可将数组条目转换为单个数组,条目中的每一原素用逗号分隔。

hobbies =[“basketball”,”football”,”swimming”]print(“My hobbies are:”+ “,”.join(hobbies))# My hobbies are: basketball, football, swimming

12.排序元音字母数下列方式可排序数组中元音字母(‘a’,‘e’,‘i’,‘o’,‘u’)的数目。

import redef countvowels(str):return len(len(re.findall(r[aeiou], str, re.IGNORECASE)))countvowels(foobar)# 3countvowels(gym)# 0

13.第一个字母恢复小写下列方式需用于将取值数组的第一个字母转换为小写。

def decapitalize(string):return str[:1].lower()+ str[1:]decapitalize(FooBar)# fooBardecapitalize(FooBar)# fooBar

14.平面化下列方式采用递归来展开潜在的深度条目。

def spread(arg):ret =[]for i in arg:if isinstance(i, list):ret.extend(i)else:ret.append(i)return retdef deepflatten(lst):result =[]result.extend(spread(list(map(lambda x: deepflatten(x) if type(x)== list else x, lst))))return resultdeepflatten([1,[2],[[3],4],5])# [1,2,3,4,5]

15.差异该方式只保留第一个迭代器中的值,从而发现三个迭代器之间的差异。

def difference(a, b):seta = set(a)setb = set(b)comparison = seta.difference(setb)return list(comparison)difference([1,2,3],[1,2,4])# [3]

16.寻找差异上面的方式在将取值的函数应用于三个条目的每一元素后,回到三个条目之间的差值。

def differenceby(a, b, fn):b = set(map(fn, b))return [item for item in a if fn(item) not in b]from math import floordifferenceby([2.1,1.2],[2.3,3.4],floor)# [1.2]differenceby([{x:2 },{ x:1 }],[{x:1 }], lambda v : v[x])# [{ x:2 }]

17.链式函数调用

下列方式可在一行中调用多个函数。

def add(a, b):return a + bdef subtract(a, b):return a – ba, b =4,5print((subtract if a > b else add)(a, b))# 9

18.检查和多次重复值

下列方式采用 set()方法仅包含唯一原素的事实来检查和条目与否具有多次重复值。

def hasduplicates(lst):return len(lst)!= len(set(lst))

x =[1,2,3,4,5,5]y =[1,2,3,4,5]hasduplicates(x)# Truehasduplicates(y)# False

19.合并三个词典

下列方式需用于合并三个词典。

def mergetwodicts(a, b):c = a.copy()# make a copy of ac.update(b)# modify keys and values of a with the ones from breturn ca ={ x:1,y:2}b ={ y:3,z:4}print(mergetwodicts(a, b))# {y:3,x:1,z:4}

在Python 3.5及更高版本中,你还能执行下列操作:

def mergedictionaries(a, b)return {**a,**b}a ={ x:1,y:2}b ={ y:3,z:4}print(mergedictionaries(a, b))# {y:3,x:1,z:4}

20.将三个条目转换成一个词典

下列方式可将三个条目转换成一个词典。

def todictionary(keys, values):return dict(zip(keys, values))

keys =[“a”,”b”,”c”]values =[2,3,4]print(todictionary(keys, values))# {a:2,c:4,b:3}

21.采用枚举

下列方式将字典作为输入,然后仅回到该字典中的键。

list =[“a”,”b”,”c”,”d”]for index, element in enumerate(list):print(“Value”, element,”Index “, index,)#(Value,a,Index ,0)#(Value,b,Index ,1)#(Value,c,Index ,2)#(Value,d,Index ,3)

22.排序所需时间

下列程序标识符需用于排序执行特定标识符所需的时间。

import timestarttime = time.time()a =1b =2c = a + bprint(c)#3endtime = time.time()totaltime = endtime – starttimeprint(“Time:”, totaltime)#(Time:,1.1205673217773438e-05)

23.Try else 指令

你能将 else 子句作为 try/except 块的一部分,如果没有抛出异常,则执行该子句。

try:2*3except TypeError:print(“An exception was raised”)else:print(“Thank God, no exceptions were raised.”)#Thank God, no exceptions were raised.

24.查找最常见原素

下列方式回到条目中出现的最常见原素。

def mostfrequent(list):return max(set(list), key = list.count)

list =[1,2,1,2,3,2,1,4,2]mostfrequent(list)

25.回文

下列方式可检查和取值的数组与否为回文结构。该方式首先将数组转换为小写,然后从中删掉非字母数字字符串。最后,它会将新的数组与反转版本展开比较。

def palindrome(string):from re import subs = sub([\W],, string.lower())return s == s[::-1]palindrome(taco cat)# True

26.没有 if-else 语句的简单排序器

下列程序标识符将展示如何编写一个不采用 if-else 条件的简单排序器。

import operatoraction ={“+”: operator.add,”-“: operator.sub,”/”: operator.truediv,”*”: operator.mul,”**”: pow}print(action[-](50,25))# 25

27.原素次序打乱

下列算法通过实现 Fisher-Yates算法在新条目中展开排序来将条目中的原素次序随机打乱。

from copy import deepcopyfrom random import randintdef shuffle(lst):templst = deepcopy(lst)m = len(templst)while (m):m -=1i = randint(0, m)templst[m], templst = templst, templst[m]return templst

foo =[1,2,3]shuffle(foo)# [2,3,1], foo =[1,2,3]

28.条目扁平化

下列方式可使条目扁平化,类似于JavaScript中的[].concat(…arr)。

def spread(arg):ret =[]for i in arg:if isinstance(i, list):ret.extend(i)else:ret.append(i)return retspread([1,2,3,[4,5,6],[7],8,9])# [1,2,3,4,5,6,7,8,9]

29.变量交换

下列是交换三个变量的快速方式,而且无需采用额外的变量。

def swap(a, b):return b, aa, b =-1,14swap(a, b)# (14,-1)

下列程序标识符显示了如何在字典中没有包含要查找的键的情形下获得默认值。

d ={a:1,b:2}print(d.get(c,3))# 3以上就是你在日常工作中可能会用上的一些标识符短片,希望对你有所帮助。

30个Python实用代码片段
30个Python实用代码片段

本文转载来自:https://www.52hwl.com/3011.html

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务