收藏!20条非常实用的Python代码实例

开发 后端
据说Python之父-Guido Van Rossum打算让CPython更快,速度直接翻五倍,这是实实在在的好消息。

 Python一直以来被诟病速度慢,影响开发效率,希望这次Guido老爷子能帮python打一场漂亮的翻身仗。

[[412878]]

这篇文章不准备介绍Python速度如何,而是给大家带来一些常用且实用的Python代码实例,几乎是开发者必备的知识点。

1、合并两个字典

Python3.5之后,合并字典变得容易起来。我们可以通过**符号解压字典,并将多个字典传入{}中,实现合并。

 

  1. def Merge(dict1, dict2):  
  2.     res = {**dict1, **dict2}  
  3.     return res  
  4.        
  5. # 两个字典 
  6. dict1 = {"name""Joy""age": 25} 
  7. dict2 = {"name""Joy""city""New York"
  8. dict3 = Merge(dict1, dict2)  
  9. print(dict3) 

 

输出:

 

  1. {'name''Joy''age': 25, 'city''New York'

2、链式比较

python有链式比较的机制,在一行里支持多种运算符比较。相当于拆分多个逻辑表达式,再进行逻辑与操作。

 

  1. a = 5 
  2.  
  3. print(2 < a < 8) 
  4. print(1 == a < 3) 

 

输出:

 

  1. True 
  2. False 

 

3、重复打印字符串

将一个字符串重复打印多次,一般使用循环实现,但有更简易的方式可以实现。

 

  1. n = 5 
  2. string = "Hello!" 
  3.  
  4. print(string * n) 

 

输出:

 

  1. Hello!Hello!Hello!Hello!Hello! 

4、检查文件是否存在

我们知道Python有专门处理系统交互的模块-os,它可以处理文件的各种增删改查操作。

那如何检查一个文件是否存在呢?os模块可以轻松实现。

 

  1. from os import path 
  2.  
  3. def check_for_file(): 
  4.     print("Does file exist:", path.exists("data.csv")) 
  5.  
  6. if __name__=="__main__"
  7.     check_for_file() 

 

输出:

 

  1. Does file exist: False 

5、检索列表最后一个元素

在使用列表的时候,有时会需要取最后一个元素,有下面几种方式可以实现。

 

  1. my_list = ['banana''apple''orange''pineapple'
  2.  
  3. #索引方法 
  4. last_element = my_list[-1] 
  5.  
  6. #pop方法 
  7. last_element = my_list.pop() 

 

输出:

 

  1. 'pineapple' 

6、列表推导式

列表推导式是for循环的简易形式,可以在一行代码里创建一个新列表,同时能通过if语句进行判断筛选

 

  1. def get_vowels(string): 
  2.     return [vowel for vowel in string if vowel in 'aeiou']  
  3.  
  4. print("Vowels are:", get_vowels('This is some random string')) 

 

输出:

 

  1. Vowels are: ['i''i''o''e''a''o''i'

7、计算代码执行时间

python中time模块提供了时间处理相关的各种函数方法,我们可以使用它来计算代码执行的时间。

 

  1. import time 
  2.  
  3. start_time = time.time() 
  4.  
  5. total = 0 
  6. for i in range(10): 
  7.   total += i 
  8. print("Sum:", total) 
  9.  
  10. end_time = time.time() 
  11. time_taken = end_time - start_time 
  12. print("Time: ", time_taken) 

 

输出:

 

  1. Sum: 45 
  2.  
  3. Time: 0.0009975433349609375 

 

8、查找出现次数最多的元素

使用max方法找出列表中出现次数最多的元素。

 

  1. def most_frequent(list): 
  2.   return max(set(list), key=list.count
  3.  
  4. mylist = [1,1,2,3,4,5,6,6,2,2] 
  5. print("出现次数最多的元素是:", most_frequent(mylist)) 

 

输出:

 

  1. 出现次数最多的元素是: 2 

9、将两个列表转换为字典

有两个列表,将列表A里的元素作为键,将列表B里的对应元素作为值,组成一个字典。

 

  1. def list_to_dictionary(keys, values): 
  2.   return dict(zip(keys, values)) 
  3.  
  4. list1 = [1, 2, 3] 
  5. list2 = ['one''two''three'
  6.  
  7. print(list_to_dictionary(list1, list2)) 

 

输出:

 

  1. {1: 'one', 2: 'two', 3: 'three'

10、异常处理

Python提供了try...except...finally的方式来处理代码异常,当然还有其他组合的方式。

 

  1. a, b = 1,0 
  2.  
  3. try: 
  4.     print(a/b) 
  5. except ZeroDivisionError: 
  6.     print("Can not divide by zero"
  7. finally: 
  8.     print("Executing finally block"

 

输出:

 

  1. Can not divide by zero 
  2. Executing finally block 

 

11、反转字符串

使用切片操作对字符串进行反转,这是比较直接有效的方式。

这也可以用来检测回文数。

 

  1. str = "Hello World" 
  2.  
  3. print("反转后字符串是:", str[::-1]) 

 

输出:

 

  1. 反转后字符串是: dlroW olleH 

12、字符串列表组成单个字符串

使用join方法将字符串列表组成单个字符串。

 

  1. list = ["Hello""world""Ok""Bye!"
  2. combined_string = " ".join(list) 
  3.  
  4. print(combined_string) 

 

输出:

 

  1. Hello world Ok Bye! 

13、返回字典缺失键的默认值

字典中的get方法用于返回指定键的值,如果键不在字典中返回默认值 None 或者设置的默认值。

 

  1. dict = {1:'one', 2:'two', 4:'four'
  2.  
  3. #returning three as default value 
  4. print(dict.get(3, 'three')) 
  5.  
  6. print("原始字典:", dict)  

 

输出:

 

  1. three 
  2. 原始字典: {1: 'one', 2: 'two', 4: 'four'

 

14、交换两个变量的值

在不使用临时变量的前提下,交换两个变量的值。

 

  1. a, b = 5, 10 
  2.  
  3. # 方法1 
  4. a, b = b, a 
  5.  
  6. # 方法2 
  7. def swap(a,b): 
  8.   return b,a 
  9. swap(a,b) 

 

15、正则表达式

正则表达式用来匹配处理字符串,python中的re模块提供了全部的正则功能。

 

  1. import re 
  2.  
  3. text = "The rain in spain" 
  4. result = re.search("rain", text) 
  5.  
  6. print(True if result else False

 

输出:

 

  1. True 

16、筛选值

python中的filter方法可以用来进行值的筛选。

 

  1. my_list = [0,1,2,3,6,7,9,11] 
  2.  
  3. result = filter(lambda x: x % 2!=0, my_list) 
  4.  
  5. print(list(result)) 

 

输出:

 

  1. [1, 3, 7, 9, 11] 

17、统计字频

判断字符串每个元素出现的次数,可以用collections模块中的Counter方法来实现,非常简洁。

 

  1. from collections import Counter 
  2. result = Counter('banana'
  3. print(result) 

 

输出:

 

  1. Counter({'a': 3, 'n': 2, 'b': 1}) 

18、变量的内存占用

如何输出python中变量的内存占用大小,可以通过sys模块来实现。

 

  1. import sys 
  2.  
  3. var1 = 15 
  4. list1 = [1,2,3,4,5] 
  5.  
  6. print(sys.getsizeof(var1)) 
  7. print(sys.getsizeof(list1)) 

 

输出:

 

  1. 28 
  2. 104 

 

19、链式函数调用

在一行代码中调用多个函数。

 

  1. def add(a, b): 
  2.     return a + b 
  3.  
  4. def subtract(a, b): 
  5.     return a - b 
  6.  
  7. a, b = 5, 10 
  8.  
  9. print((add if b > a else subtract)(a,b)) 

 

输出:

 

  1. 15 

20、从列表中删除重复项

删除列表中重复项一般可以通过遍历来筛选去重,或者直接使用集合方法。

 

  1. list1 = [1,2,3,3,4,'John''Ana''Mark''John'
  2.  
  3. # 方法1 
  4. def remove_duplicate(list_value): 
  5.     return list(set(list_value)) 
  6. print(remove_duplicate(list1)) 
  7.  
  8. # 方法2 
  9. result = [] 
  10. [result.append(x) for x in list1 if x not in result] 
  11. print(result) 

 

输出:

 

  1. [1, 2, 3, 4, 'Ana''John''Mark'
  2. [1, 2, 3, 4, 'John''Ana''Mark'

 

责任编辑:华轩 来源: 今日头条
相关推荐

2021-05-23 16:23:22

Python 开发编程语言

2020-05-28 08:59:40

Python机器学习开发

2020-09-14 11:10:43

Python代码

2020-08-21 10:25:02

PythonWget

2021-11-03 08:04:41

电脑快捷键电脑硬件

2023-08-03 07:05:28

电脑软件工具

2020-07-10 15:41:41

Python代码编程语言

2022-06-27 19:01:04

Python应用程序数据

2015-11-02 09:25:07

jQuery代码片段

2022-07-21 14:38:17

PythonShell

2020-07-03 07:58:01

开源开发软件

2021-01-25 09:36:00

Python代码文件

2021-04-15 11:21:26

Shell脚本Linux

2021-04-11 07:56:42

ShellLinux

2011-07-07 09:01:52

HTML 5

2022-01-05 07:07:36

网络

2022-06-24 10:02:43

PythonShell脚本

2019-10-31 08:22:39

shell脚本Linux

2019-11-05 10:07:26

数据科学Python

2018-04-10 16:20:38

Python性能优化
点赞
收藏

51CTO技术栈公众号