美文网首页
Python_内置

Python_内置

作者: 违规昵称不予展示 | 来源:发表于2018-08-07 20:56 被阅读0次

1.enumerate() 返回索引和内容

cities = ['shanghai', 'beijing', 'shenzhen', 'chengdu']
i = 0
for c in cities:
    print i+1, '-->', c
    i += 1
1 --> shanghai
2 --> beijing
3 --> shenzhen
4 --> chengdu

可以改写为

>>> for i,city in enumerate(cities):
...     print i+1, '-->', c
...
1 --> chengdu
2 --> chengdu
3 --> chengdu
4 --> chengdu

2.zip() 两个列表一一对应时用的

>>> names = ['leo', 'jack', 'john', 'james']
>>> colors = ['red', 'green', 'blue', 'yellow']
>>> n = min(len(names), len(colors))
>>> for i in range(n):
...     print names[i], '-->', colors[i]
...
leo --> red
jack --> green
john --> blue
james --> yellow

改写为

>>> for name, color in zip(names, colors):
...     print name, '-->', color
...
leo --> red
jack --> green
john --> blue
james --> yellow

如果两个序列有10000000的长度,当然用izip

import itertools
>>> for name, color in itertools.izip(names, colors):
...     print name, '-->', color
...
leo --> red
jack --> green
john --> blue
james --> yellow

现在py3.6中默认zip为izip

3. 变量交换

多个变量之间的交换,相信很多有c,c++语言基础的同学对这个再熟悉不过了,比如我们经典的冒泡排序,就会用这一招,看看比较传统的做法:

>>> x = 1
>>> y = 2
>>> print '>>before:x={},y={}'.format(x,y)
>>> tmp=y
>>> y=x
>>> x=tmp
>>> print '>>after:x={},y={}'.format(x,y)


>>before:x=1,y=2
>>after:x=2,y=1

更优雅的做法是:

>>> x=1
>>> y=2
>>> print '>>before:x={},y={}'.format(x,y)
>>> x,y = y,x
>>> print '>>after:x={},y={}'.format(x,y)


>>before:x=1,y=2
>>after:x=2,y=1

4.读取字典

字典是我们经常使用的数据结构,对于字典的访问和读取,如果我们的读取的字典的key为空怎么办,一般我们需要一个缺省值,菜鸟的写法:

>>> students = {'Lili': 18, 'Sam': 25}
>>> if 'Susan' in students:
...     student = students['Susan']
... else:
...     student = 'unknow'
...
>>> print 'Susan is {} years old'.format(student)
Susan is unknow years old

大佬的写法是:

>>> student = students.get('Susan','unknow')
>>> print 'Susan is {} years old'.format(student)
Susan is unknow years old

5.循环查找

我们经常会在一个大的循环中作搜索业务,比如从一个文件中搜索关键字,比如从文件名列表中查找一些特殊的文件名,想当然的写法如下

>>> target_letter = 'd'
>>> letters = ['a', 'b', 'c']
>>> found = False
>>> for letter in letters:
...     if letter == target_letter:
...         print 'Found'
...         found = True
...         break
...
>>> if not found:
...     print 'Not found'
...
Not found

上面的写法是传统的c,c++写法,Python里面有更简洁的写法:

>>> for letter in letters:
...     if letter == target_letter:
...         print 'Found'
...         break
... else:
...     print 'Not found'
...
Not found

6.文件读取

通常来说,我们要打开一个文件,然后对文件的内容进行循环读取和处理,菜鸟的写法如下:

>>> f = open('data.txt')
>>> try:
...     text = f.read()
...     for line in text.split('\n'):
...         print line
... finally:
...     f.close()
...
hello
world

更优雅的写法:

>>> with open('data.txt')as f:
...     for line in f:
...         print line.strip('\n')
...
hello
world

7.关于锁的写法

对于并发操作尤其是多线程的操作,我们对同一块内存进行读写操作的时候,通常我们都加锁保护的,想当然的写法如下:

>>> import threading
>>> lock = threading.Lock()
>>> lock.acquire()
True
>>> try:
...     print 'Citical part,do something...'
... finally:
...     lock.release()
...
Citical part,do something...

上面这样的写法我自己写了很多年,觉得没有啥问题啊,后来遇到下面的写法,瞬间膜拜了!

>>> lock = threading.Lock()
>>> with lock:
...     print 'Citical part,do somethin...'
...
Citical part,do somethin...

相关文章

  • Python_内置

    1.enumerate() 返回索引和内容 可以改写为 2.zip() 两个列表一一对应时用的 改写为 如果两个序...

  • Python函数的学习笔记_函数

    Python_函数 isinstance(a,int) #判断a是否为int If not (isinstance...

  • Python容器的学习笔记_容器

    Python_容器 my_str ='abcd\tc' # my_str[0]='Q' print(my_str)...

  • 文章链接集合

    作者:Gakki Python Python_查找字典中相同与不同的部分[https://www.jianshu....

  • 第十五章 Python_常用内置模块

    一、sys 模块 二、os 模块 os.path.exists("path") path 需要时字符串类型如果pa...

  • matplotlib之tick_params( 参数 )

    参考链接:matplotlib命令与格式:tick_params参数刻度线样式设置_Python_开码河粉-CSD...

  • Python 编译安装

    目录 http://see.sl088.com/wiki/Python_%E7%BC%96%E8%AF%91%E5...

  • python_(:

    先看下object类中对new()方法的定义: object将new()方法定义为静态方法,并且至少需要传递一个参...

  • Python_函数

    Python_函数 在我们有面向对象思想后,会更加容易的理解。所以函数的章节内容会较为精简。 调用函数 Pytho...

  • python安装

    点击进入python_官方网站下载所需版本 python2.7安装 1、双击安装文件 2、选择默认,为所有用户安装...

网友评论

      本文标题:Python_内置

      本文链接:https://www.haomeiwen.com/subject/hvtzvftx.html