Python有一些技巧对你来说是新知识,但是还有一些技巧会让你的代码效率大幅提升。

本文总结了一下自己用到的一些Python高级编程技巧,希望对大家有帮助。

列表生成器

a=[1,2,3]
[x*x for x in a if x>1]
[4, 9]

集合生成器

a=[1,2,3]
s = {x*x for x in a if x>1}
s
{4, 9}
type(s)
set

字典生成器

a=[1,2,3]
{str(x):x+1 for x in a if x>1}
{'2': 3, '3': 4}

range

list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list(range(3,10))
[3, 4, 5, 6, 7, 8, 9]

filter用于过滤数据

list(filter(lambda x:x%3==0, range(10)))
[0, 3, 6, 9]

collections.namedtuple给列表或者元组命名

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(11, 22)
p.x
11
p.y
22

random的使用

from random import randint
randint(1,10)
1

统计序列元素的频度和TOP N

from collections import Counter
c = Counter('aaabbbbccccccddddddeeeeee')
c
Counter({'a': 3, 'b': 4, 'c': 6, 'd': 6, 'e': 6})
c.most_common(3)
[('c', 6), ('d', 6), ('e', 6)]

将字典按value排序

from random import randint
keys = 'abcdefg'
d = {x:randint(90,100) for x in keys}
d
{'a': 90, 'b': 98, 'c': 100, 'd': 97, 'e': 95, 'f': 93, 'g': 92}
d.items()
dict_items([('a', 90), ('b', 98), ('c', 100), ('d', 97), ('e', 95), ('f', 93), ('g', 92)])
sorted(d.items(), key=lambda x : x[1])
[('a', 90), ('g', 92), ('f', 93), ('e', 95), ('d', 97), ('b', 98), ('c', 100)]

获得多个词典的key的交集

from random import randint, sample
dd1 = {x:randint(90,100) for x in sample('abcdefghij', 5)}
dd2 = {x:randint(90,100) for x in sample('abcdefghij', 5)}
dd3 = {x:randint(90,100) for x in sample('abcdefghij', 5)}
dd1
{'h': 99, 'f': 94, 'c': 91, 'i': 99, 'b': 95}
dd2
{'b': 95, 'g': 91, 'h': 98, 'f': 100, 'd': 92}
dd3
{'h': 95, 'g': 99, 'a': 100, 'd': 96, 'i': 92}
mp = map(dict.keys, (dd1, dd2, dd3))
list(mp)
[dict_keys(['h', 'f', 'c', 'i', 'b']),
dict_keys(['b', 'g', 'h', 'f', 'd']),
dict_keys(['h', 'g', 'a', 'd', 'i'])]
from functools import reduce
reduce(lambda x,y: x&y, mp)
{'h'}

怎样让字典按照插入有序

from collections import OrderedDict
d = OrderedDict()
d['x'] = 1
d['y'] = 2
d['a'] = 2
d['b'] = 2
d
OrderedDict([('x', 1), ('y', 2), ('a', 2), ('b', 2)])

怎样实现长度为N的队列功能

from collections import deque
d = deque([], 3)
d.append(1)
d.append(2)
d.append(3)
d.append(4)
d
deque([2, 3, 4])

怎样同时遍历多个集合

names = [x for x in 'abcdefg']
ages = [x for x in range(21, 28)]
scores = [randint(90,100) for x in range(7)]
for name,age,score in zip(names, ages, scores):
print(name,age,score)
a 21 95
b 22 99
c 23 94
d 24 95
e 25 100
f 26 96
g 27 95

怎样串行的遍历多个集合

lista = (randint(1,10) for x in range(10))
listb = [randint(90,100) for x in range(20)]
from itertools import chain
for x in chain(lista, listb):
print(x, end=',')
5,10,3,1,8,7,6,5,6,8,92,95,91,98,95,93,96,95,94,98,92,90,91,91,99,96,90,100,94,99,

使用多种分隔符替换字符串

s = 'a,b;c/d'
import re
re.sub(r'[,;/]', '-', s)
'a-b-c-d'

字符串的模糊搜索与部分替换

s = 'things happend in 2017-08-09, it is a sunddy'
re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\2-\1-\3', s)
'things happend in 08-2017-09, it is a sunddy'

列表JOIN时如果有数字元素怎么办

print('\t'.join([str(x) for x in ['a','b',33,4.0,'e']]))
a	b	33	4.0	e

如何使用多线程-方法1

from threading import Thread

def func(x):
print(x, x*x*x) ts = []
for x in range(10):
t = Thread(target=func, args=(x,))
t.start()
ts.append(t) for t in ts:
t.join() print('main thread over')
0 0
1 1
2 8
3 27
4 64
5 125
6 216
7 343
8 512
9 729
main thread over

如何使用多线程-方法2

以下的输出错乱,是正常的,因为多个线程同时print就错乱了

from threading import Thread

class MyThread(Thread):
def __init__(self, x):
Thread.__init__(self)
self.x = x def run(self):
print(self.x, self.x*self.x*self.x) ts = []
for x in range(10):
t = MyThread(x)
t.start()
ts.append(t) for t in ts:
t.join() print('main thread over')
0 0
1 1
2 3 27
8
45 64
6 216
125
7 343
8 512
9 729
main thread over

关注我,学习更多Python基础、数据分析、大数据、推荐系统知识;

Python的几个高级编程技巧的更多相关文章

  1. [libgdx游戏开发教程]使用Libgdx进行游戏开发(11)-高级编程技巧 Box2d和Shader

    高级编程技巧只是相对的,其实主要是讲物理模拟和着色器程序的使用. 本章主要讲解利用Box2D并用它来实现萝卜雨,然后是使用单色着色器shader让画面呈现单色状态:http://files.cnblo ...

  2. 【转载】 python sort、sorted高级排序技巧

    这篇文章主要介绍了python sort.sorted高级排序技巧,本文讲解了基础排序.升序和降序.排序的稳定性和复杂排序.cmp函数排序法等内容,需要的朋友可以参考下 Python list内置so ...

  3. python高级编程技巧

    由python高级编程处学习 http://blog.sina.com.cn/s/blog_a89e19440101fb28.html Python列表解析语法[]和生成 器()语法类似 [expr  ...

  4. 关于Python的10大实用编程技巧

      Python 是一种通用的脚本开发语言,比其他编程语言更加简单.易学,其面向对象特性甚至比Java.C#..NET更加彻底,因此非常适合快速开发. Python 已经成为最受欢迎的程序设计语言之一 ...

  5. python 的一些高级编程技巧

    正文: 本文展示一些高级的Python设计结构和它们的使用方法.在日常工作中,你可以根据需要选择合适的数据结构,例如对快速查找性的要求.对数据一致性的要求或是对索引的要求等,同时也可以将各种数据结构合 ...

  6. Python高级编程技巧(转)

    译文:http://blog.jobbole.com/61171/ 本文展示一些高级的Python设计结构和它们的使用方法.在日常工作中,你可以根据需要选择合适的数据结构,例如对快速查找性的要求.对数 ...

  7. python基础之面向对象高级编程

    面向对象基本知识: 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 是一个模板,模板中包装了多个"函数"供使用(可以讲多函数中公用的变量封装到对象中) ...

  8. python sort、sorted高级排序技巧(转)

    add by zhj: 没找到原文.可以按多个维度进行排序,而且可以指定他们的排序方向,如果维度都是数字,排序比较容易,用+/-号就可以 指定排序方向.否则,就调用多次sorted进行排序了,而且要按 ...

  9. Linux Shell 高级编程技巧4----几个常用的shell脚本例子

    4.几个常用的shell脚本例子    4.0.在写脚本(同样适用在编程的时候),最好写好完善的注释    4.1.kill_processes.sh(一个杀死进程的脚本) #!/bin/bash c ...

随机推荐

  1. Android按钮绑定四种方式

    public class MainActivity extends Activity implements OnClickListener{ @Override protected void onCr ...

  2. 一次完整的HTTP请求与响应涉及哪些知识?

    Java技术栈 www.javastack.cn 优秀的Java技术公众号 作者:Ruheng 地址:http://www.jianshu.com/p/c1d6a294d3c0 本文以HTTP请求和响 ...

  3. 豌豆荚Redis集群方案:Codis

    Codis简介 Codis是一个分布式Redis解决方案,对于上层的应用来说,连接到CodisProxy和连接原生的RedisServer没有明显的区别(不支持的命令列表),上层应用可以像使用单机的R ...

  4. 课程笔记-lisanke

    1.判断真需求假需求 真需求:所有人都需要的功能 假需求:只有自己需要的功能 2.找到目标用户 ①不要直接询问是否需要这个功能 ②旁敲侧击式提问:用户使用了什么方式?之前都是怎么做的? case:购物 ...

  5. java_打印流

    public class transientTest { /** * 反序列化操作2 * 序列化后的文件被修改后进行反序列化时会报错 * 决绝方法: * 手动添加序列号Serializable中有声明 ...

  6. 2018-11-19-WPF-在image控件用鼠标拖拽出矩形

    title author date CreateTime categories WPF 在image控件用鼠标拖拽出矩形 lindexi 2018-11-19 15:35:13 +0800 2018- ...

  7. ThinkPHP无限分类模块设计

    public function catelist(){ $cate=D('Cate'); //var_dump($cate->gettree());exit; $cateres=$cate-&g ...

  8. Tensorflow入门篇

     参考Tensorflow中文网(http://www.tensorfly.cn/tfdoc/get_started/introduction.html) ,写一个入门. 1.打开pyCharm,新建 ...

  9. js封装设置获取cookie

    var docCookies = { getItem: function (sKey) { return decodeURIComponent(document.cookie.replace(new ...

  10. 《DSP using MATLAB》Problem 8.15

    代码: %% ------------------------------------------------------------------------ %% Output Info about ...