当前位置: 首页 > 编程日记 > 正文

python标准库学习4

>>> os.environ["HOME"]
'C:\\Users\\Administrator'>>> os.getcwd() #获得当前的目录
'D:\\new'
>>> os.getenv("QTDIR")  #获取环境变量的值
'D:\\vs2010-qt-src-4.7.4\\qt-src-4.7.4'
os.putenv(varname, value)  #设置环境变量的值os.mkdir(path[, mode])
>>> os.mkdir("aa")
>>> os.rmdir("aa")
>>>os.makedirs("aa\\bb\\cc") 多级目录
os.removedirs(path)¶
os.remove("d:\\new\\hello.txt")  #删除文件,如果是目录的话,出错
os.rename("test.txt","a.txt")  random.randint(a, b)
Return a random integer N such that a <= N <= b.
random.choice(seq)
Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.
random.random()
Return the next random floating point number in the range [0.0, 1.0).
random.shuffle(x[, random])  随机排序序列
random.uniform(a, b)¶返回a<=N<=b之间的浮点数
random.randrange([start], stop[, step])想当于choice(range(start, stop, step))
>>> random.random()        # Random float x, 0.0 <= x < 1.0
0.37444887175646646
>>> random.uniform(1, 10)  # Random float x, 1.0 <= x < 10.0
1.1800146073117523
>>> random.randint(1, 10)  # Integer from 1 to 10, endpoints included
7
>>> random.randrange(0, 101, 2)  # Even integer from 0 to 100
26
>>> random.choice('abcdefghij')  # Choose a random element
'c'>>> items = [1, 2, 3, 4, 5, 6, 7]
>>> random.shuffle(items)
>>> items
[7, 3, 2, 5, 6, 4, 1]>>> random.sample([1, 2, 3, 4, 5],  3)  # Choose 3 elements
[4, 1, 5]>>> datetime.MAXYEAR
9999
>>> datetime.MINYEAR
1>>> a=datetime.date(2011,2,1)
>>> a.today()
datetime.date(2011, 11, 26)
>>> a.year
2011
>>> a.month
2
>>> a.day
1>>> import time
>>> from datetime import date
>>> today = date.today()
>>> today
datetime.date(2007, 12, 5)
>>> my_birthday = date(today.year, 6, 24)
>>> if my_birthday < today:
...     my_birthday = my_birthday.replace(year=today.year + 1)
>>> my_birthday
datetime.date(2008, 6, 24)
>>> time_to_birthday = abs(my_birthday - today)  #计算日期之差
>>> time_to_birthday.days
202>>> datetime.now()   #当前时间
datetime.datetime(2011, 11, 26, 10, 40, 10, 283000)
>>> datetime.utcnow()
datetime.datetime(2011, 11, 26, 2, 40, 34, 809000)
>>> a=date(2005,7,14)  #日期和时间进行合并
>>> t=time(12,30,12)
>>> datetime.combine(a,t)
datetime.datetime(2005, 7, 14, 12, 30, 12)
>>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
>>> dt
datetime.datetime(2006, 11, 21, 16, 30)>>> from datetime import timedelta, datetime, tzinfo
>>> class GMT1(tzinfo):
...     def __init__(self):         # DST starts last Sunday in March
...         d = datetime(dt.year, 4, 1)   # ends last Sunday in October
...         self.dston = d - timedelta(days=d.weekday() + 1)
...         d = datetime(dt.year, 11, 1)
...         self.dstoff = d - timedelta(days=d.weekday() + 1)
...     def utcoffset(self, dt):
...         return timedelta(hours=1) + self.dst(dt)
...     def dst(self, dt):
...         if self.dston <=  dt.replace(tzinfo=None) < self.dstoff:
...             return timedelta(hours=1)
...         else:
...             return timedelta(0)
...     def tzname(self,dt):
...          return "GMT +1"
...
>>> class GMT2(tzinfo):
...     def __init__(self):
...         d = datetime(dt.year, 4, 1)
...         self.dston = d - timedelta(days=d.weekday() + 1)
...         d = datetime(dt.year, 11, 1)
...         self.dstoff = d - timedelta(days=d.weekday() + 1)
...     def utcoffset(self, dt):
...         return timedelta(hours=1) + self.dst(dt)
...     def dst(self, dt):
...         if self.dston <=  dt.replace(tzinfo=None) < self.dstoff:
...             return timedelta(hours=2)
...         else:
...             return timedelta(0)
...     def tzname(self,dt):
...         return "GMT +2"
...
>>> gmt1 = GMT1()
>>> # Daylight Saving Time
>>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
>>> dt1.dst()
datetime.timedelta(0)
>>> dt1.utcoffset()
datetime.timedelta(0, 3600)
>>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
>>> dt2.dst()
datetime.timedelta(0, 3600)
>>> dt2.utcoffset()
datetime.timedelta(0, 7200)
>>> # Convert datetime to another time zone
>>> dt3 = dt2.astimezone(GMT2())
>>> dt3     # doctest: +ELLIPSIS
datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
>>> dt2     # doctest: +ELLIPSIS
datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
>>> dt2.utctimetuple() == dt3.utctimetuple()
Trueclass datetime.time(hour[, minute[, second[, microsecond[, tzinfo]]]])
>>> a=time(10,46,12)
>>> a.min
datetime.time(0, 0)
>>> a.max
datetime.time(23, 59, 59, 999999)
>>> a.hour
10
>>> a.minute
46
>>> a.second
12
>>> a.microsecond
0class collections.Counter([iterable-or-mapping])
A Counter is a dict subclass for counting hashable objects.
>>> # Tally occurrences of words in a list
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
...     cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})>>> # Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall('\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]>>> c = Counter(['eggs', 'ham'])
>>> c['bacon']                              # count of a missing element is zero
0
>>> c['sausage'] = 0                        # counter entry with a zero count
>>> del c['sausage']                        # del actually removes the entry>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> list(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']most_common([n])  #出现次数最多的n个
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> d = Counter(a=1, b=2, c=3, d=4)
>>> c.subtract(d)
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> sum(c.values())  # total of all counts
4
>>> list(c)
['a', 'c', 'b', 'd']
>>> set(c)
set(['a', 'c', 'b', 'd'])
>>> dict(c)
{'a': 4, 'c': 0, 'b': 2, 'd': -2}
>>> c.items()
[('a', 4), ('c', 0), ('b', 2), ('d', -2)]
>>> c.most_common()[:-2:-1]    # c.most_common()[:-n:-1] n least #common elements[('d', -2)]
>>> c+=Counter()
>>> c
Counter({'a': 4, 'b': 2})
>>> c.clear()
>>> c
Counter()>>> c = Counter(a=3, b=1)
>>> d = Counter(a=1, b=2)
>>> c + d                       # add two counters together:  c[x] + d[x]
Counter({'a': 4, 'b': 3})
>>> c - d                       # subtract (keeping only positive counts)
Counter({'a': 2})
>>> c & d                       # intersection:  min(c[x], d[x])
Counter({'a': 1, 'b': 1})
>>> c | d                       # union:  max(c[x], d[x])
Counter({'a': 3, 'b': 2})>>> from collections import deque
>>> d = deque('ghi')                 # make a new deque with three items
>>> for elem in d:                   # iterate over the deque's elements
...     print elem.upper()
G
H
I>>> d.append('j')                    # add a new entry to the right side
>>> d.appendleft('f')                # add a new entry to the left side
>>> d                                # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])>>> d.pop()                          # return and remove the rightmost item
'j'
>>> d.popleft()                      # return and remove the leftmost item
'f'
>>> list(d)                          # list the contents of the deque
['g', 'h', 'i']
>>> d[0]                             # peek at leftmost item
'g'
>>> d[-1]                            # peek at rightmost item
'i'>>> list(reversed(d))                # list the contents of a deque in reverse
['i', 'h', 'g']
>>> 'h' in d                         # search the deque
True
>>> d.extend('jkl')                  # add multiple elements at once
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
>>> d.rotate(1)                      # right rotation
>>> d
deque(['l', 'g', 'h', 'i', 'j', 'k'])
>>> d.rotate(-1)                     # left rotation
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])>>> deque(reversed(d))               # make a new deque in reverse order
deque(['l', 'k', 'j', 'i', 'h', 'g'])
>>> d.clear()                        # empty the deque
>>> d.pop()                          # cannot pop from an empty deque
Traceback (most recent call last):File "<pyshell#6>", line 1, in -toplevel-d.pop()
IndexError: pop from an empty deque>>> d.extendleft('abc')              # extendleft() reverses the input order
>>> d
deque(['c', 'b', 'a'])def tail(filename, n=10):'Return the last n lines of a file'return deque(open(filename), n)def moving_average(iterable, n=3):# moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0# http://en.wikipedia.org/wiki/Moving_averageit = iter(iterable)d = deque(itertools.islice(it, n-1))d.appendleft(0)s = sum(d)for elem in it:s += elem - d.popleft()d.append(elem)yield s / float(n)def delete_nth(d, n):d.rotate(-n)d.popleft()d.rotate(n)class collections.defaultdict([default_factory[, ...]])
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]>>> d = {}
>>> for k, v in s:
...     d.setdefault(k, []).append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
...     d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]>>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
>>> d = defaultdict(set)
>>> for k, v in s:
...     d[k].add(v)
...
>>> d.items()
[('blue', set([2, 4])), ('red', set([1, 3]))]>>> def heapsort(iterable):
...     'Equivalent to sorted(iterable)'
...     h = []
...     for value in iterable:
...         heappush(h, value)
...     return [heappop(h) for i in range(len(h))]
...
>>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> h = []
>>> heappush(h, (5, 'write code'))
>>> heappush(h, (7, 'release product'))
>>> heappush(h, (1, 'write spec'))
>>> heappush(h, (3, 'create tests'))
>>> heappop(h)
(1, 'write spec')#coding=utf-8
#堆的实例from heapq import heappush, heappop, heappushpop, heapify, heapreplace, nlargest,\nsmallestheap=[]heappush(heap,"A");
heappush(heap,"C");
heappush(heap,"B");print heapheappop(heap)   #弹出堆中最小的元素
print heapvar=heappushpop(heap,"D")  #返回并弹出堆中最小的元素,并且将D压入堆
print var
print heapvar=heapreplace(heap,"E")  #返回并弹出堆中最小的元素,并且将D压入堆,
print var
print heaplist=[1,2,3,4,5,6,7,8,9,0]
heapify(list);
print listprint nlargest(3,list)   #返回堆中最大的3个
print nsmallest(3,list)  #返回堆中最小的3个

相关文章:

通过三个直观步骤理解ROC曲线

作者 | Valeria Cortez来源 | DeepHub IMBAROC曲线是一个分类模型效果好坏评判的的可视化表示。在这篇文章中&#xff0c;我将分三个步骤头开始构建ROC曲线。步骤1&#xff1a;获取分类模型预测当我们训练一个分类模型时&#xff0c;我们得到得到一个结果的概率。在这种情况下&…

JAVA 实现 快速排序算法

2019独角兽企业重金招聘Python工程师标准>>> /*** 快速排序* * param list*/public static void fastSorted(int[] list, int i, int j) {if (i > j) {return;}int needToSortLen j;int referIndex i;while (i ! j) {while (list[referIndex] < list[j] &am…

Net 下安装、调试的常见问题与错误!!!

作者&#xff1a;多人 出处&#xff1a;csdn Q:新建项目时出错&#xff1a;Visual Studio .NET 已检测到指定Web服务器运行的不是ASP.NET 1.1版。您将无法运行ASP.NET Web应用程序或服务。Ahttp://support.microsoft.com/default.aspx?scidkb;en-us;817267--------------…

joomla 1.7遇到的麻烦——不能删除模板的解决办法

虽然最近了解了不少的 joomla 1.7的扩展&#xff0c;但大多都没有什么实战经验&#xff0c;所以从今天开始 准备不同的试用各类插件、并以实战的方式来记录这个过程。不过&#xff0c;在做这些之前&#xff0c;我试用了几个免费的模板&#xff0c;感觉还可以&#xff0c;不过毕…

疫情排查节时86%?不会代码也能玩转模型训练?腾讯大神揭秘语音语义及AutoML黑科技 | 内含福利...

出品 | AI科技大本营&#xff08;ID:rgznai100&#xff09;2020年7月3日&#xff0c;AI ProCon 2020 AI开发者万人大会&#xff0c;隆重举行&#xff01;作为CSDN策划并主办的系列技术「开发者大会」之一&#xff0c;本次大会通过线上直播的方式&#xff0c;吸引到了10000开发者…

js调用ios的方法

摘要 在做h5应用的时&#xff0c;有时有些功能js并不能实现的特别完美。比如下载进度条或上传文件进度等。如果能调用ios或者android的方法&#xff0c;实现进度&#xff0c;以及文件上传或者下载列表更好一些。如果使用第三方的js插件。又要考虑到ios和android的版本问题&…

可以弹出确认对话框的自定义Web服务器控件ConfirmButton

作者&#xff1a;活靶子[原创] 出处&#xff1a;AspxBoy.Com 经常在论坛里看到类似这样的问题&#xff1a;“…如何在点击删除按钮的时候弹出个确认删除对话框”。下面我们来自己写一个这样的自定义Web服务器控件!思路如下&#xff1a;继承System.Web.UI.WebControls.Butt…

阿里巴巴副总裁司罗:达摩院如何搭建NLP技术体系?

出品 | AI科技大本营&#xff08;ID:rgznai100&#xff09;司罗把人工智能分为四个层面。在计算智能层面&#xff0c;近年来取得了一定成就&#xff0c;而在更高层面的感知、认知和创造智能上还在探索中。感知智能是指找出自然界的实体&#xff0c;比如找到新闻、故事中的人名、…

数字化校园passport

公共表&#xff1a;aspnetdb->membership,role,..... 用户表&#xff1a;用户名&#xff0c;昵称&#xff0c;真实姓名。tel,qq,mobile,email,用户类别 用户类别&#xff1a; 教师 学生 家长 贵宾 校友 网友 学年学期 班级 年级段 备课级组 处室 教师相关表&#xff1a; 任课…

fullPage教程 -- 整屏滚动效果插件 fullpage详解

为什么80%的码农都做不了架构师&#xff1f;>>> 本文为 H5EDU 机构官方 HTML5培训 教程&#xff0c;主要介绍&#xff1a;fullPage教程 -- 整屏滚动效果插件 fullpage详解 1、引用文件[html] view plain copy print?在CODE上查看代码片派生到我的代码片 <link …

用DataReader还是DataSet?

作者&#xff1a;Jonathan Goodyear 出处&#xff1a;网络 我经常听到有人问这个问题&#xff1a;“在ASP.NET Web应用程序中我应该用DataReader类还是DataSet类呢&#xff1f;”在很多文章以及新闻组的贴子中我经常看到这样的误解&#xff0c;即认为DataReader&#xff…

张钹院士:探索第三代人工智能,需要勇闯无人区的人才

整理 | 夕颜出品 | AI科技大本营&#xff08;ID:rgznai100&#xff09;【导读】7 月 3-4 日&#xff0c;由 CSDN 主办的第三届 AI 开发者大会&#xff08;AI ProCon 2020&#xff09;在线上举行。本次大会有超万人报名参与&#xff0c;参与人群覆盖 50 领域、4000 家企业。其中…

C#删除文件夹

我们知道在c#中如果一个文件夹中有内容的话&#xff0c;直接使用Directory.Delete(文件夹)&#xff1b;是删不掉的&#xff0c;那么如何进行删除&#xff1f;下面这个两个方法可以帮助你。 1、采用递归的方式&#xff0c;先删除文件夹中的文件&#xff0c;然后删除空文件夹。 p…

PHPNow升级PHP版本为5.3.5的方法

在WIN上有时候需要测试一些PHP程序&#xff0c;又不会自行独立配置环境&#xff0c;那么PHPNow是非常好的选择&#xff0c;这篇文章主要为大家分享下如果将phpnow的php版本升级为5.3.5在WIN上有时候需要测试一些PHP程序&#xff0c;又不会自行独立配置环境&#xff0c;那么PHPN…

针对《评人工智能如何走向新阶段》一文,继续发布国内外的跟贴留言427-438条如下:

427&#xff0c;SNN机理性测试 SNN利用时空处理&#xff0c;脉冲稀疏性和较高的内部神经元带宽来最大化神经形态计算的能量效率。尽管可以在这种情况下使用常规的基于硅的技术&#xff0c;但最终的神经元突触电路需要多个晶体管和复杂的布局&#xff0c;从而限制了集成密度。论…

C#程序设计语言Version2.0简介

[翻译] lover_P 2004-01-26 ------------------------------------------------------------------------------------------------------------------------------------------------------------ 本文翻译自Microsoft官方参考材料&#xff0c;提供给我们的计算机科学技术网的…

腾讯布局移动应用商店 总下载量累计达40亿次

腾讯布局移动应用商店 总下载量累计达40亿次 腾讯应用中心产品总监祝涛29日在上海表示&#xff0c;移动互联网近年来在国内快速发展&#xff0c;腾讯应用中心作为国内最大的软件商店之一&#xff0c;截至目前总下载量已超过40亿次。 祝涛在当天由腾讯应用中心举行的一个开发者/…

iOS开源JSON解析库MJExtension

iOS中JSON与NSObject互转有两种方式&#xff1a;1、iOS自带类NSJSONSerialization 2、第三方开源库SBJSON、JSONKit、MJExtension。项目中一直用MJExtension来进行JSON与Model的互转&#xff0c;非常方便、强大&#xff0c;接下来介绍一下这个轻量、强大的开源库。 1、什么是MJ…

针对《评人工智能如何走向新阶段》一文,继续发布国内外的跟贴留言439-448条如下:

439&#xff0c;彩虹一号无人机实现人类永不落地的追求 日媒&#xff1a;中国亮出杀手锏 世界各国一直在研究提高飞机的续航能力 国内研制的彩虹一号无人机采用人工智能和其他高新技术&#xff0c;飞行高度30000米&#xff0c;并终于研制成功实现人类永不落地的追求。 440&a…

Asp.Net中查询域名的Whois信息

作者&#xff1a;活靶子 出处&#xff1a;AspxBoy.Com 演示http://www.aspxboy.com/whois.aspx拷贝代码请到这里 http://www.aspxboy.com/WhoisCode.htm<% Page Language"C#" %><% Import Namespace"System.Net.Sockets" %><% Import …

Python 安装 xlsx模块

为什么80%的码农都做不了架构师&#xff1f;>>> Python 安装 xlsx模块 很多时候自动化测试时测试用例是写在excel中的如何读取转换成字典是一个比较关键的问题&#xff0c;使用pip命令安装模块如下&#xff1a;pip install openpyxl 验证使用的python代码如下&…

利用WebClient和WebRequest类获得网页源代码C#

作者&#xff1a;不详 请速与本人联系 GetPageHtml.aspx<% Page language"c#" validateRequest "false" Codebehind"GetPageHtml.aspx.cs" AutoEventWireup"false" Inherits"eMeng.Exam.GetPageHtml" %><!DO…

针对《评人工智能如何走向新阶段》一文,继续发布国内外的跟贴留言449-456条如下:

449&#xff0c;IBM发布重磅产品&#xff1a;推出新的人工智能能力。IBM研发AI向用户提供自动化的运维&#xff08;生态&#xff09;服务。 IBM新任CEO Arvind Krishna5月6日在IBM举办的“Think digital”大会上说&#xff1a;IBM致力于帮助企业&#xff08;用户&#xff09;加…

POI如何使用已有Excel作为模板二三事

关于POIPOI是Apache的一个开源项目&#xff0c;起初的目标是允许用户使用java代码来对Excel进行操作&#xff0c;发展到今天POI本身支持的范围已经逐步扩展到对Microsoft Office主要产品&#xff0c;包括&#xff1a;Excel\Word\PPT\Visio的全面支持&#xff0c;目前稳定版本为…

Graphviz样例之无向图

Graphviz是一个开源软件&#xff0c;有源码&#xff0c;支持不同平台。linux系统下使用XDot程序显示dot格式的文件。 Graphviz显示图形时&#xff0c;可以选择不同的策略进行布局和布线显示图形。 Graphviz的官方网站&#xff08;点击进入&#xff09;&#xff1a;Graphviz | G…

使用command-privilege给H3C、华为设备的用户帐号授权

一、H3C设备的权限默认分为0-3这四种级别 数值越小&#xff0c;用户的级别越低 (1)访问权限0 级 : ping、tracert、telnet 等网络诊断小程序&#xff0c;不可以dis current (2)监控权限 1级: dis current、reset、可开debug这种高级系统诊断工具&#xff0c;不能进入system视图…

针对《评人工智能如何走向新阶段》一文,继续发布国内外的跟贴留言457-465条如下:

457&#xff0c;常识推理攻关进展 人工智能要变得像人一样聪明常识推理能力是必备的 机器缺乏常识推理&#xff0c;何时到了破局的时候&#xff1f;&#xff01;这是迄今为止一直困扰人工智能50多年的难题。 OpenAI于去年发布GPT—2&#xff0c;它是一个具有15亿参数的通用语…

使用 Global.asax 文件

作者&#xff1a;未知 请速与本人联系 Global.asax 文件 除了编写 UI 代码外&#xff0c;开发人员还可以将应用程序级别的逻辑和事件处理代码添加到他们的 Web 应用程序中。此代码不处理 UI 的生成&#xff0c;并且一般不为响应个别页请求而被调用。相反&#xff0c;它负…

安装hadoop下的sqoop1.99.3及配置问题全解决

2016年8月27日&#xff0c;解决sqoop先下载的是sqoop1.99.7&#xff0c;结果配置的时候&#xff0c;出现了没有server/conf目录&#xff0c;以及启动时出现无法配置错误./bin/sqoop.sh server startyqubuntu:/opt/sqoop-1.99.7$ ./bin/sqoop.sh server startSetting conf dir: …

让Asp.NET的DataGrid可排序、可选择、可分页

‘***************************************************************‘Author: 李洪根‘MAIL: lihonggen0gci-corp.com‘专栏&#xff1a; http://www.csdn.net/develop/author/netauthor/lihonggen0/‘如需引用&#xff0c;请指明出处&#xff01; CSDN论坛VB版欢迎您&#…