filter sorted heapq counter namedtuple  reduce deque pickle islice re.split endswith stat os

#filter

>>> aa = [1,2,3,45,6,7]

>>> list(filter(lambda x:x>3,aa))

>>> [45, 6, 7]

#sorted

>>> sorted(d.items(),key=lambda x:x[1],reverse=True)

#heapq

>>> import heapq

>>> heap.nlargest(3,[1,2,2,2,3,4,4,45,5,6])

#counter

>>> from collections import Counter

>>> aa = Counter([1,2,2,2,3,4,4,45,5,6])

>>> aa.most_common(3)

#namedtuple

>>> from collection import namedtuple

>>> Stu = namedtuple('Stu',['name','age','sex'])

>>> s2 = Stu('jm',16,'male')

>>> s2.name

'jm'

#reduce

>>> dl = [{'d':3,'a':2,'b':4},{'f':3,'g':2,'b':4},{'d':3,'f':2,'b':4}]

>>> reduce(lambda a,b : a & b ,map(dict.keys,dl))

#deque

>>> from collections import deque

>>> q = deque([],5)

>>> q.append(1)

>>> import pickle

>>> pickle.dump(q,open('save.pkl','wb'))

>>> pickle.load(open('save.pkl','rb'))

deque([1], maxlen=5)

#islice

>>> from functools import islice

>>> list(islice(range(10),4,6))

[4, 5]

>>> def query_by_order(d,a,b=None):

...     a -= 1

...     if b is None:

...             b= a+1

...     return list(islice(d,a,b))

#re.split

>>> re.split('[;,|]+','ab;ffff|gdhgdjh,jfjje')

['ab', 'ffff', 'gdhgdjh', 'jfjje']

#endswith stat os 可执行权限

>>> import stat

>>> import os

>>> for fn in os.listdir():

...     if fn.endswith(('.py','.sh')):

...             fs = os.stat(fn)

...             os.chmod(fn,fs.st_mode | stat.S_IXUSR)

# re.sub 替换字符串

>>> re.sub(r'(\d{4})-(\d{2})-(\d{2})',r'\2/\3/\1',log)

# iterator 和iterable的区别为迭代器只能使用一次,可迭代对象可使用多次
from collections import Iterable, Iterator
import requests class WeatherIterator(Iterator):
def __init__(self, caties):
self.caties = caties
self.index = 0 def __next__(self):
if self.index == len(self.caties):
raise StopIteration
city = self.caties[self.index]
self.index += 1
return self.get_weather(city) def get_weather(self, city):
url = 'http://wthrcdn.etouch.cn/weather_mini?city=' + city
r = requests.get(url)
data = r.json()['data']['forecast'][0]
return city, data['high'], data['low'] class WeatherIterable(Iterable):
def __init__(self, cities):
self.cities = cities def __iter__(self):
return WeatherIterator(self.cities) def show(w):
for x in w:
print(x) w = WeatherIterable(['北京', '上海', '广州'] * 10)
show(w)

#yield生成器对象自动维护迭代状态

from collections import Iterable

class PrimeNumbers(Iterable):
def __init__(self, a, b):
self.a = a
self.b = b def __iter__(self):
for k in range(self.a, self.b + 1):
if self.is_prime(k):
yield k def is_prime(self, k):
return False if k < 2 else all(map(lambda x: k % x, range(2, k))) pn = PrimeNumbers(1, 30)
for n in pn:
print(n)
#reversed 反向迭代实现
from decimal import Decimal class FloatRange:
def __init__(self, a, b, step):
self.a = Decimal(str(a))
self.b = Decimal(str(b))
self.step = Decimal(str(step)) def __iter__(self):
t = self.a
while t <= self.b:
yield float(t)
t += self.step def __reversed__(self):
t = self.b
while t >= self.a:
yield float(t)
t -= self.step fr = FloatRange(3.0, 4.0, 0.2)
for x in fr:
print(x)
print('-' * 20)
for x in reversed(fr):
print(x)

Python内置函数复习的更多相关文章

  1. python内置函数

    python内置函数 官方文档:点击 在这里我只列举一些常见的内置函数用法 1.abs()[求数字的绝对值] >>> abs(-13) 13 2.all() 判断所有集合元素都为真的 ...

  2. python 内置函数和函数装饰器

    python内置函数 1.数学相关 abs(x) 取x绝对值 divmode(x,y) 取x除以y的商和余数,常用做分页,返回商和余数组成一个元组 pow(x,y[,z]) 取x的y次方 ,等同于x ...

  3. Python基础篇【第2篇】: Python内置函数(一)

    Python内置函数 lambda lambda表达式相当于函数体为单个return语句的普通函数的匿名函数.请注意,lambda语法并没有使用return关键字.开发者可以在任何可以使用函数引用的位 ...

  4. [python基础知识]python内置函数map/reduce/filter

    python内置函数map/reduce/filter 这三个函数用的顺手了,很cool. filter()函数:filter函数相当于过滤,调用一个bool_func(只返回bool类型数据的方法) ...

  5. Python内置函数进制转换的用法

    使用Python内置函数:bin().oct().int().hex()可实现进制转换. 先看Python官方文档中对这几个内置函数的描述: bin(x)Convert an integer numb ...

  6. Python内置函数(12)——str

    英文文档: class str(object='') class str(object=b'', encoding='utf-8', errors='strict') Return a string  ...

  7. Python内置函数(61)——str

    英文文档: class str(object='') class str(object=b'', encoding='utf-8', errors='strict') Return a string ...

  8. 那些年,很多人没看懂的Python内置函数

    Python之所以特别的简单就是因为有很多的内置函数是在你的程序"运行之前"就已经帮你运行好了,所以,可以用这个的特性简化很多的步骤.这也是让Python语言变得特别的简单的原因之 ...

  9. Python 内置函数笔记

    其中有几个方法没怎么用过, 所以没整理到 Python内置函数 abs(a) 返回a的绝对值.该参数可以是整数或浮点数.如果参数是一个复数,则返回其大小 all(a) 如果元组.列表里面的所有元素都非 ...

随机推荐

  1. MYSQL:基于哈希的索引和基于树的索引有什么区别?

    B+树是一个平衡的多叉树.B+树从根节点到叶子节点的搜索效率基本相当,不会出现大幅波动. 哈希索引采用一定的哈希算法,把键值换成新的哈希值,检索时不需要类似B+树那样从根节点逐级查找,只需一次哈希算法 ...

  2. #lua中编写shader的方式

    lua中编写shader的方式 1. 字符串拼接 类似于下面这种 vertDefaultSource = "\n".."\n" .. "attribu ...

  3. 每日一问:LayoutParams 你知道多少?

    前面的文章中着重讲解了 View 的测量流程.其中我提到了一句非常重要的话:View 的测量匡高是由父控件的 MeasureSpec 和 View 自身的 `LayoutParams 共同决定的.我们 ...

  4. Linux学习之编译运行.c(C语言)文件

    在Linux命令行界面下,创建文件hello.c,进入vim编辑器,编辑一个简单的C语言文件 分解C语言文件执行过程,要经过预编译.编译.汇编.连接四个步骤后才能执行, 预编译:gcc -E hell ...

  5. 【Gamma】“北航社团帮”发布说明——小程序v3.0

    目录 Gamma版本新功能 小程序v3.0新功能 新功能列表 新功能展示 这一版修复的缺陷 Gamma版本的已知问题和限制 小程序端 网页端 运行.安装与发布 运行环境的要求 安装与发布 小程序 网页 ...

  6. gcc命令详解

    gcc命令使用GNU推出的基于C/C++的编译器,是开放源代码领域应用最广泛的编译器,具有功能强大,编译代码支持性能优化等特点.目前,GCC可以用来编译C/C++.FORTRAN.JAVA.OBJC. ...

  7. kaggle house price

    kaggle 竞赛入门 导入常用的数据分析以及模型的库 数据处理 Data fields 去除异常值 处理缺失值 分析 Utilities Exploratory Data Analysis Corr ...

  8. 关于 Object.defineProperty()

    通常,定义或者修改一个JS对象,有以下方式: // 1. 字面量 let obj = { name: 'cedric', age: 18 } // 2. new Object() let obj = ...

  9. 在GitHub中创建目录

    需求:假定我们需要在 Answer 目录下创建一个目录 [注]GitHub无法单独创建一个空目录,但是可以在创建一个文件的同时创建它的所属目录 1.点击进入所需的目录 Answer 2.点击“Crea ...

  10. [原创] Agilent 34410A 表与计算机通讯

    1. 接口选择 万用电表出厂时选定为HP-IB接口,应选择为RS-232接口 E:I/O MENU – 2:INTERFACE 选择RS-232 2. 设定波特率 默认9600 E:I/O MENU ...