首页 > 应用开发 > Python > 22条最常用Python代码,快收藏!
今日份知识你摄入了么?
在这篇文章里,我想和你分享22个python代码片段,可以帮你解决一些日常问题。

图片来自作者
1
空格分隔多个输入
这段代码可以让你一次进行多个用空格分隔的输入,每当你要解决编程竞赛的问题时,这段代码就可以派上用场。
## Taking Two Integers as input a,b = map( int, input.split) print( "a:",a) print( "b:",b) ## Taking a List as input arr = list( map( int, input.split)) print( "Input List:",arr)
2
同时访问Index索引和值
enumerate这个内置函数可以让你在or循环中同时找到索引和值。
arr = [ 2, 4, 6, 3, 8, 10] forindex,value inenumerate(arr): print( f"At Index {index}The Value Is -> {value}" ) '''Output At Index 0 The Value Is -> 2 At Index 1 The Value Is -> 4 At Index 2 The Value Is -> 6 At Index 3 The Value Is -> 3 At Index 4 The Value Is -> 8 At Index 5 The Value Is -> 10 '''
3
检查内存使用情况
这段代码可以用于检查对象的内存使用情况。
4
输出某个变量的唯一ID
id这个函数能让你找到变量的唯一id,你只需要在这个方法中传递变量名。
5
检查Anagram
一个Anagram的意思是,通过重新排列一个单词的字母,在恰好使用一次每个原始字母的情况下,组成另一个新词。
defcheck_anagram( first_word, second_word): returnsorted(first_word) == sorted(second_word) print(check_anagram( "silent", "listen")) # True print(check_anagram( "ginger", "danger")) # False
6
合并两个字典
当你在处理数据库和JSON文件,需要将来自不同文件或表的多个数据合并到同一个文件中时,用这个代码会很方便。合并两个字典会有一些风险,比如要是出现了重复的key怎么办?还好,我们对这种情况也是有解决方案的。
basic_information = { "name":[ 'karl', 'Lary'], "mobile":[ "0134567894", "0123456789"]} academic_information = { "grade":[ "A", "B"]} details = dict## Combines Dict ## Dictionary Comprehension Method details = {key: value fordata in(basic_information, academic_information) forkey,value indata.items} print(details) ## Dictionary unpacking details = {**basic_information ,**academic_information} print(details) ## Copy and Update Method details = basic_information.copy details.update(academic_information) print(details)
7
检查一个文件是否存在
我们要确保代码中使用的文件还存在。Python使管理文件变得很容易,因为Python有读写文件的内置语法。
# Brute force Method importos.path fromos importpath defcheck_for_file: print( "File exists: ",path.exists( "data.txt")) if__name__== "__main__": check_for_file ''' File exists: False '''
8
在给定范围内,算所有数的平方
在这段代码中,我们利用内置函数itertools找到给定范围内每个整数的平方。
# METHOD 1 fromitertools importrepeat n = 5 squares = list( map( pow, range( 1, n+ 1), repeat( 2))) print(squares) # METHOD 2 n = 6 squares = [i** 2fori inrange( 1,n+ 1)] print(squares) """Output [1, 4, 9, 16, 25] """
9
将两个list转换为dictionary
以下这个方法可以将两个列表转换为字典。
list1 = [ 'karl', 'lary', 'keera'] list2 = [ 28934, 28935, 28936] # Method 1: zip dictt0 = dict(zip(list1,list2)) # Method 2: dictionary comprehension dictt1 = {key:value forkey,value in zip(list1,list2)} # Method 3: Using a For Loop (Not Recommended) tuples = zip(list1, list2) dictt2 = {} forkey, value in tuples: ifkey in dictt2: pass else: dictt2[key] = value print(dictt0, dictt1, dictt2, sep = "\n")
10
对字符串列表进行排序
当你拿到一个学生姓名的列表,并想对所有姓名进行排序时,这段代码会非常有用。
list1 = [ "Karl", "Larry", "Ana", "Zack"] # Method 1: sort list1.sort # Method 2: sorted sorted_list = sorted(list1) # Method 3: Brute Force Method size = len(list1) fori inrange(size): forj inrange(size): iflist1[i] < list1[j]: temp = list1[i] list1[i] = list1[j] list1[j] = temp print(list1)
11
用if和Else来理解列表
当你希望根据某些条件筛选数据结构时,这段代码非常有用。
12
添加来自两个列表的元素
假设你有两个列表,并想通过添加它们的元素将它们合并到一个列表中,这段代码在这种场景中会很有用。
maths = [ 59, 64, 75, 86] physics = [ 78, 98, 56, 56] # Brute Force Method list1 = [ maths[ 0]+physics[ 0], maths[ 1]+physics[ 1], maths[ 2]+physics[ 2], maths[ 3]+physics[ 3] ] # List Comprehension list1 = [x + y forx,y inzip(maths,physics)] # Using Maps importoperator all_devices = list( map(operator.add, maths, physics)) # Using Numpy Library importnumpy asnp list1 = np.add(maths,physics) '''Output [137 162 131 142] '''
13
对dictionary列表进行排序
当你有一个字典列表时,你可能希望借助key的帮助将它们按顺序排列起来。
dict1 = [ { "Name": "Karl", "Age": 25}, { "Name": "Lary", "Age": 39}, { "Name": "Nina", "Age": 35} ] ## Using sort dict1.sort(key= lambdaitem: item.get( "Age")) # List sorting using itemgetter fromoperator importitemgetter f = itemgetter( 'Name') dict1.sort(key=f) # Iterable sorted function dict1 = sorted(dict1, key= lambdaitem: item.get( "Age")) '''Output [{'Age': 25, 'Name': 'Karl'}, {'Age': 35, 'Name': 'Nina'}, {'Age': 39, 'Name': 'Lary'}] '''
14
计算Shell的时间
有时,了解shell或一段代码的执行时间是很重要的,这样可以用最少的时间取得更好的算法。
# METHOD 1 importdatetime start = datetime.datetime.now """ CODE """ print(datetime.datetime.now-start) # METHOD 2 importtime start_time = time.time main print( f"Total Time To Execute The Code is {(time.time - start_time)}" ) # METHOD 3 importtimeit code = ''' ## Code snippet whose execution time is to be measured [2,6,3,6,7,1,5,72,1].sort ''' print(timeit.timeit(stmy = code,number = 1000))
15
检查字符串中的子字符串
我日常都会遇到的一件事,就是检查一个字符串是否包含某个子字符串。与其他编程语言不同,python为此提供了一个很好的关键字。
addresses = [ "12/45 Elm street", '34/56 Clark street', '56,77 maple street', '17/45 Elm street' ] street = 'Elm street' fori inaddresses: ifstreet ini: print(i) '''output 12/45 Elm street 17/45 Elm street '''
16
字符串格式
代码最重要的部分是输入、逻辑和输出。在编程过程中,这三个部分都需要某种特定格式,以得到更好地、更易于阅读的输出。 python提供了多种方法来改变字符串的格式。
name = "Abhay" age = 21 ## METHOD 1: Concatenation print( "My name is "+name+ ", and I am "+str(age)+ " years old.") ## METHOD 2: F-strings (Python 3+) print(f "My name is {name}, and I am {age} years old") ## METHOD 3: Join print( ''.join(["My name is ", name, ", and I am ", str(age), " years old"])) ## METHOD 4: modulus operator print("My name is %s, and I am %d years old." % (name, age)) ## METHOD 5: format(Python 2 and 3) print("My name is {}, and I am {} years old".format(name, age))
17
错误处理
与Java和c++一样,python也提供了try、except和finally 来处理异常错误的方法。
# Example 1 try: a = int(input( "Enter a:")) b = int(input( "Enter b:")) c = a/b print(c) except: print( "Can't divide with zero") # Example 2 try: #this will throw an exception ifthe file doesn 't exist. fileptr = open("file.txt","r") except IOError: print("File not found") else: print("The file opened successfully") fileptr.close # Example 3 try: fptr = open("data.txt",'r ') try: fptr.write("Hello World!") finally: fptr.close print("File Closed") except: print("Error")
18
列表中最常见的元素
最后,如果你的时间不是很紧张,并且又想快速的提高,最重要的是不怕吃苦,建议你可以扩我伪xin python7762 ,那个真的很不错,很多人进步都很快,需要你不怕吃苦哦!大家可以去添加上看一下~
下面方法可以返回出列表中出现频率最高的元素。
19
在没有if – else的情况下计算
这段代码展示了在不使用任何if-else条件的情况下,如何简单地编写一个计算器。
importoperator action = { "+": operator.add, "-": operator.sub, "/": operator.truediv, "*": operator.mul, "**": pow } print(action[ '*']( 5, 5)) # 25
20
Chained Function调用
在python中,你可以在同一行代码调用多个函数。
defadd( a,b): returna+b defsub( a,b): returna-b a,b = 9, 6 print((sub ifa > b elseadd)(a, b))
21
交换数值
以下是在不需要另一个额外变量的情况下交换两个数值的快速方法。
a,b = 5, 7 # Method 1 b,a = a,b # Method 2 defswap( a,b): returnb,a swap(a,b)
看到这里还是觉得自己上手困难?欢迎参加数据应用学院本周六线上免费讲座,一小时带你入门python!扫描海报二维码报名~
22
查找重复项
通过这段代码,你可以检查列表中是否有重复的值。
原文作者:Abhay Parashar
翻译作者:过儿
美工编辑:过儿
校对审稿: Jiawei Tong
原文链接:https://levelup.gitconnected.com/22-python-code-snippets-for-everyday-problems-4c6a216c33ae
Google Product Analyst 面经详解
如何为你的数据可视化找到正确的色板?
【面试技巧】如何应变面试三大模式?
狗家/IBM/微软:哪家线上Data Analyst证书求职含金量最高?
探索性数据分析实例——扒了200多天的2万条聊天记录,我发现了群聊的秘密
点「在看」的人都变好看了哦
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69997412/viewspace-2769343/ ,如需转载,请注明出处,否则将追究法律责任。