我列出的这些有用的Python代码片段,为我节省了大量的时间,并且我希望他们也能为你节省一些时间。大多数的这些片段出自寻找解决方案,查找博客和StackOverflow解决类似问题的答案。下面所有的代码片段已经在Python 3中测试。

在Python中调用一个外部命令

有时你需要通过shell或命令提示符调用一个外部命令,这在Python中通过使用subprocess模块很容易实现。

只需要运行一条命令:

import subprocess

subprocess.call(['mkdir', 'empty_folder'])

如果想运行一条命令并输出得到的结果:

import subprocess

output = subprocess.check_output(['ls', '-l'])

要说明的是上面的调用是阻塞的。

如果运行shell中内置的命令,如cd或者dir,需要指定标记shell=True:

import subprocess

output = subprocess.call(['cd', '/'], shell=True)

对于更高级的用例,可以使用 Popen constructor。

Python 3.5引进了一个新的run函数,它的行为与call和check_output很相似。如果你使用的是3.5版本或更高版本,看一看run的文档,里面有一些有用的例子。否则,如果你使用的是Python 3.5以前的版本或者你想保持向后兼容性,上面的call和check_output代码片段是你最安全和最简单的选择。

美观打印

开发时使用pprint模块替代标准的print 函数,可以让shell输出的信息更具可读性。这使得输出到shell上的字典和嵌套对象更易读。

import pprint as pp

animals = [{'animal': 'dog', 'legs': 4, 'breeds': ['Border Collie', 'Pit Bull', 'Huskie']}, {'animal': 'cat', 'legs': 4, 'breeds': ['Siamese', 'Persian', 'Sphynx']}]

pp.pprint(animals, width=1)

width参数指定一行上最大的字符数。设置width为1确保字典打印在单独的行。

按属性进行数据分组

假设你查询一个数据库,并得到如下数据:

data = [

{'animal': 'dog', 'name': 'Roxie', 'age': 5},

{'animal': 'dog', 'name': 'Zeus', 'age': 6},

{'animal': 'dog', 'name': 'Spike', 'age': 9},

{'animal': 'dog', 'name': 'Scooby', 'age': 7},

{'animal': 'cat', 'name': 'Fluffy', 'age': 3},

{'animal': 'cat', 'name': 'Oreo', 'age': 5},

{'animal': 'cat', 'name': 'Bella', 'age': 4}

]

通过动物类型分组得到一个狗的列表和一个猫的列表。幸好,Python的itertools有一个groupby函数可以让你很轻松的完成这些。

from itertools import groupby

data = [

{'animal': 'dog', 'name': 'Roxie', 'age': 5},

{'animal': 'dog', 'name': 'Zeus', 'age': 6},

{'animal': 'dog', 'name': 'Spike', 'age': 9},

{'animal': 'dog', 'name': 'Scooby', 'age': 7},

{'animal': 'cat', 'name': 'Fluffy', 'age': 3},

{'animal': 'cat', 'name': 'Oreo', 'age': 5},

{'animal': 'cat', 'name': 'Bella', 'age': 4}

]

for key, group in groupby(data, lambda x: x['animal']):

for thing in group:

print(thing['name'] + " is a " + key)

得到的输出是:

Roxie is a dog

Zeus is a dog

Spike is a dog

Scooby is a dog

Fluffy is a cat

Oreo is a cat

Bella is a cat

groupby()有2个参数:1、我们想要分组的数据,它在本例中是一个字典。2、分组函数:lambda x: x['animal']告诉groupby函数每个字典按动物的类型分组

现在通过列表推导式可以很容易地构建一个狗的列表和一个猫的列表:

from itertools import groupby

import pprint as pp

data = [

{'animal': 'dog', 'name': 'Roxie', 'age': 5},

{'animal': 'dog', 'name': 'Zeus', 'age': 6},

{'animal': 'dog', 'name': 'Spike', 'age': 9},

{'animal': 'dog', 'name': 'Scooby', 'age': 7},

{'animal': 'cat', 'name': 'Fluffy', 'age': 3},

{'animal': 'cat', 'name': 'Oreo', 'age': 5},

{'animal': 'cat', 'name': 'Bella', 'age': 4}

]

grouped_data = {}

for key, group in groupby(data, lambda x: x['animal']):

grouped_data[key] = [thing['name'] for thing in group]

pp.pprint(grouped_data)

最后得到一个按动物类型分组的输出:

{

'cat': [

'Fluffy',

'Oreo',

'Bella'

],

'dog': [

'Roxie',

'Zeus',

'Spike',

'Scooby'

]

}

StackOverflow上这个问题的答案非常有帮助,当我试图找出如何以最Pythonic的方式分组数据时,这篇文章节省了我很多时间。

删除列表中的重复元素

Python中用一行代码快速简单的删除一个列表中的重复元素(不维持顺序):

x = [1, 8, 4, 5, 5, 5, 8, 1, 8]

list(set(x))

这个方法利用了set是一个不同的对象的集合这一事实。然而,set不维持顺序,因此如果你在乎对象的顺序,使用下面的技术:

from collections import OrderedDict

x = [1, 8, 4, 5, 5, 5, 8, 1, 8]

list(OrderedDict.fromkeys(x))

访问Python的For循环的索引

对于许多人来说这可能是常识,但这也是经常问的。Python的内置enumerate 函数提供索引和值的访问如下:

x = [1, 8, 4, 5, 5, 5, 8, 1, 8]

for index, value in enumerate(x):

print(index, value)

通过指定enumerate函数的start参数改变起始索引:

x = [1, 8, 4, 5, 5, 5, 8, 1, 8]

for index, value in enumerate(x, start=1):

print(index, value)

现在该索引从1到9而不是0到8

并行遍历2个集合

使用内置zip函数同时遍历2个列表,字典,等。下面是使用zip函数同时遍历2个列表的例子:

a = [1, 2, 3]

b = [4, 5, 6]

for (a_val, b_val) in zip(a, b):

print(a_val, b_val)

将输出:

1 4

2 5

3 6

创建对象的Copy

Python中可以使用通用的copy函数复制一个对象。浅拷贝是通过使用copy.copy调用的:

import copy

new_list = copy.copy(old_list)

深拷贝:

import copy

new_list = copy.deepcopy(old_list)

这个StackOverflow问题对于复制一个列表的各种方法给出了很好的解释。如果你不熟悉浅拷贝和深拷贝之间的差异看一看这个解释。

浮点除法

通过将分子或分母转换为float类型,可以确保浮点除法:

answer = a/float(b)

字符串和日期相互转换

一个常见的任务是将一个字符串转换为一个datetime对象。使用strptime 函数这将很容易做到:

from datetime import datetime

date_obj = datetime.strptime('May 29 2015  2:45PM', '%B %d %Y %I:%M%p')

它的逆操作是转换一个datetime对象为一个格式化的字符串,对datetime对象使用strftime函数:

from datetime import datetime

date_obj = datetime.now()

date_string = date_obj.strftime('%B %d %Y %I:%M%p')

有关格式化代码的列表和他们的用途,查看官方文档

解析JSON文件并写一个对象到JSON文件中

使用load函数可以解析JSON文件并构建一个Python对象。假定有一个叫做data.json的文件包括以下数据:

{

"dog": {

"lives": 1,

"breeds": [

"Border Collie",

"Pit Bull",

"Huskie"

]

},

"cat": {

"lives": 9,

"breeds": [

"Siamese",

"Persian",

"Sphynx"

]

}

}

import json

with open('data.json') as input_file:

data = json.load(input_file)

现在data是一个对象,你可以操作它像任何Python对象一样:

print(data['cat']['lives'])

output: 9

可以使用dump函数,将Python中的字典写入JSON文件中:

import json

data = {'dog': {'legs': 4, 'breeds': ['Border Collie', 'Pit Bull', 'Huskie']}, 'cat': {'legs': 4, 'breeds': ['Siamese', 'Persian', 'Sphynx']}}

with open('data.json', 'w') as output_file:

json.dump(data, output_file, indent=4)

缩进参数美观打印JSON字符串以便输出更容易阅读。在这种情况下,我们指定缩进4个空格。

有用的Python代码片段的更多相关文章

  1. Python 代码片段收藏

    list 列表相关 list 中最小值.最大值 import operator values = [1, 2, 3, 4, 5] min_index, min_value = min(enumerat ...

  2. 30+有用的CSS代码片段

    在一篇文章中收集所有的CSS代码片段几乎是不可能的事情,但是我们这里列出了一些相对于其他的更有用的代码片段,不要被这些代码的长度所吓到,因为它们都很容易实现,并且具有良好的文档.除了那些解决常见的恼人 ...

  3. 2019-01-29 VS Code创建自定义Python代码片段

    续前文[日常]Beyond的歌里最多是"唏嘘"吗? - Python分词+词频最后的想法, 发现VS Code支持用户自定义代码片段: Creating your own snip ...

  4. 【转】30+有用的CSS代码片段

    来自:WEB资源网 链接:http://webres.wang/31-css-code-snippets-to-make-you-a-better-coder/ 原文:http://www.desig ...

  5. 46 个非常有用的 PHP 代码片段

    在编写代码的时候有个神奇的工具总是好的!下面这里收集了 40+ PHP 代码片段,可以帮助你开发 PHP 项目. 这些 PHP 片段对于 PHP 初学者也非常有帮助,非常容易学习,让我们开始学习吧- ...

  6. 【转】46 个非常有用的 PHP 代码片段

    1. 发送 SMS 在开发 Web 或者移动应用的时候,经常会遇到需要发送 SMS 给用户,或者因为登录原因,或者是为了发送信息.下面的 PHP 代码就实现了发送 SMS 的功能. 为了使用任何的语言 ...

  7. Python - 代码片段,Snippets,Gist

    说明 代码片段来自网上搬运的或者自己写的 华氏温度转摄氏温度 f = float(input('请输入华氏温度: ')) c = (f - 32) / 1.8 print('%.1f华氏度 = %.1 ...

  8. 比较有用的php代码片段

    一 从网页中提取关键词 $meta = get_meta_tags('http://www.emoticode.net/'); $keywords = $meta['keywords']; // Sp ...

  9. python 代码片段26

    #coding=utf-8 ''' 使用空格而不是tab 因为无论在什么平台上开发,你的代码总是有可能会被移动或是复制到 另一不同架构的机器上,win32是4个空格,unix是8个空格,干脆 还是使用 ...

随机推荐

  1. Tomcat中配置MySQL数据库连接池

    Web开发中与数据库的连接是必不可少的,而数据库连接池技术很好的优化了动态页与数据库的连接,相比单个连接数据库连接池节省了很大的资源.用一个通俗的比喻:如果一个人洗澡需花一桶水,那一百个人就要花一百桶 ...

  2. Linux下 iptables防火墙 放开相关port 拒绝相关port 及查看已放开port

    我用的是fedora 14 1. 查看iptables 防火墙已经开启的port:/etc/init.d/iptables status [root@hzswtb2-mpc ~]#/etc/rc.d/ ...

  3. PHP-Resque 简介

    转载于:http://blog.hsatac.net/2012/01/php-resque-introduction/ Resque 是 Github 基於 Redis 开发的 background ...

  4. mosquitto ---mosquitto-auth-plug

    https://github.com/jpmens/mosquitto-auth-plug This is a plugin to authenticate and authorize Mosquit ...

  5. uploadify onSelect

    uploadify onSelect [return false]停止选择 $("#fileEleId").uploadify({ 'width': _option.width, ...

  6. Java模拟公司置办货物系统(二)

    採用MVC风格,将数据写入文件,模拟公司置办货物系统.  A类表示普通员工,B类表示部门精力,C类表示採购部,D类表示资源管理部. 订单状态 1.表示申请状态 2.表示通过审批 3.表示未通过审批 4 ...

  7. Atitit.web预览播放视频的总结

    Atitit.web预览播放视频的总结 1. 浏览器类型的兼容性(chrome,ff,ie) 1 2. 操作系统的兼容性 1 3. 视频格式的内部视频格式跟播放器插件的兼容性.. 2 4. 指定播放器 ...

  8. Makefile 使用小结

    Makefile的基本格式 #目标:依赖(条件) # 命令 #all: add.c sub.c dive.c mul.c main.c # gcc add.c sub.c div.c mul.c ma ...

  9. Spring学习11-Spring使用proxool连接池 管理数据源

    Spring 一.Proxool连接池简介及其配置属性概述   Proxool是一种Java数据库连接池技术.是sourceforge下的一个开源项目,这个项目提供一个健壮.易用的连接池,最为关键的是 ...

  10. 0062 Spring MVC的文件上传与下载--MultipartFile--ResponseEntity

    文件上传功能在网页中见的太多了,比如上传照片作为头像.上传Excel文档导入数据等 先写个上传文件的html <!DOCTYPE html> <html> <head&g ...