python标准库学习4


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

>>> 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.01.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(110)  # Random float x, 1.0 <= x < 10.0

1.1800146073117523

>>> random.randint(110)  # Integer from 1 to 10, endpoints included

7

>>> random.randrange(01012)  # Even integer from 0 to 100

26

>>> random.choice('abcdefghij')  # Choose a random element

'c'

 

>>> items = [1234567]

>>> random.shuffle(items)

>>> items

[7325641]

 

>>> random.sample([12345],  3)  # Choose 3 elements

[415]

 

>>> datetime.MAXYEAR

9999

>>> datetime.MINYEAR

1

 

>>> a=datetime.date(2011,2,1)

>>> a.today()

datetime.date(20111126)

>>> a.year

2011

>>> a.month

2

>>> a.day

1

 

>>> import time

>>> from datetime import date

>>> today = date.today()

>>> today

datetime.date(2007125)

>>> my_birthday = date(today.year, 624)

>>> if my_birthday < today:

...     my_birthday = my_birthday.replace(year=today.year + 1)

>>> my_birthday

datetime.date(2008624)

>>> time_to_birthday = abs(my_birthday - today)  #计算日期之差

>>> time_to_birthday.days

202

 

>>> datetime.now()   #当前时间

datetime.datetime(20111126104010283000)

>>> datetime.utcnow()

datetime.datetime(2011112624034809000)

>>> a=date(2005,7,14)  #日期和时间进行合并

>>> t=time(12,30,12)

>>> datetime.combine(a,t)

datetime.datetime(2005714123012)

>>> dt = datetime.strptime("21/11/06 16:30""%d/%m/%y %H:%M")

>>> dt

datetime.datetime(200611211630)

 

>>> from datetime import timedelta, datetime, tzinfo

>>> class GMT1(tzinfo):

...     def __init__(self):         # DST starts last Sunday in March

...         d = datetime(dt.year, 41)   # ends last Sunday in October

...         self.dston = - timedelta(days=d.weekday() + 1)

...         d = datetime(dt.year, 111)

...         self.dstoff = - 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, 41)

...         self.dston = - timedelta(days=d.weekday() + 1)

...         d = datetime(dt.year, 111)

...         self.dstoff = - 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(200611211630, tzinfo=gmt1)

>>> dt1.dst()

datetime.timedelta(0)

>>> dt1.utcoffset()

datetime.timedelta(03600)

>>> dt2 = datetime(2006614130, tzinfo=gmt1)

>>> dt2.dst()

datetime.timedelta(03600)

>>> dt2.utcoffset()

datetime.timedelta(07200)

>>> # Convert datetime to another time zone

>>> dt3 = dt2.astimezone(GMT2())

>>> dt3     # doctest: +ELLIPSIS

datetime.datetime(2006614140, tzinfo=<GMT2 object at 0x...>)

>>> dt2     # doctest: +ELLIPSIS

datetime.datetime(2006614130, tzinfo=<GMT1 object at 0x...>)

>>> dt2.utctimetuple() == dt3.utctimetuple()

True

 

class datetime.time(hour[, minute[, second[, microsecond[, tzinfo]]]])

>>> a=time(10,46,12)

>>> a.min

datetime.time(00)

>>> a.max

datetime.time(235959999999)

>>> a.hour

10

>>> a.minute

46

>>> a.second

12

>>> a.microsecond

0

 

class collections.Counter([iterable-or-mapping])

A Counter is 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 1in -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_average

    it = iter(iterable)

    = deque(itertools.islice(it, n-1))

    d.appendleft(0)

    = sum(d)

    for elem in it:

        += elem - d.popleft()

        d.append(elem)

        yield / 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', [24]), ('red', [1]), ('yellow', [13])]

 

>>> d = {}

>>> for k, v in s:

...     d.setdefault(k, []).append(v)

...

>>> d.items()

[('blue', [24]), ('red', [1]), ('yellow', [13])]

 

>>> s = 'mississippi'

>>> d = defaultdict(int)

>>> for 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([24])), ('red'set([13]))]

 

>>> def heapsort(iterable):

...     'Equivalent to sorted(iterable)'

...     h = []

...     for value in iterable:

...         heappush(h, value)

...     return [heappop(h) for in range(len(h))]

...

>>> heapsort([1357924680])

[0123456789]

 

>>> 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,\

    nsmallest

 

heap=[]

 

heappush(heap,"A");

heappush(heap,"C");

heappush(heap,"B");

 

print heap

 

heappop(heap)   #弹出堆中最小的元素

print heap

 

var=heappushpop(heap,"D")  #返回并弹出堆中最小的元素,并且将D压入堆

print var

print heap

 

var=heapreplace(heap,"E")  #返回并弹出堆中最小的元素,并且将D压入堆,

print var

print heap

 

list=[1,2,3,4,5,6,7,8,9,0]

heapify(list);

print list

 

print nlargest(3,list)   #返回堆中最大的3个

print nsmallest(3,list)  #返回堆中最小的3个

时间: 2024-11-16 05:26:31

python标准库学习4的相关文章

python标准库学习6

使用 apply 函数 def function(a, b):     print a, b   apply(function, ("whither", "canada?")) apply(function, (1, 2 + 3)) whither canada? 1 5 使用 apply 函数传递关键字参数 def function(a, b):     print a, b   apply(function, ("crunchy", &quo

python标准库学习9

fileinput 模块允许你循环一个或多个文本文件的内容 使用 fileinput 模块循环一个文本文件 import fileinput import sys   for line in fileinput.input("samples/sample.txt"):     sys.stdout.write("-> ")     sys.stdout.write(line)   -> We will perhaps eventually be writ

python标准库学习7

使用 os.path 模块处理文件名 import os   filename = "my/little/pony"   print "using", os.name, "..." print "split", "=>", os.path.split(filename) print "splitext", "=>", os.path.splitext(fi

python标准库学习8

使用sys重定向输出 import sys import string   class Redirect:       def _ _init_ _(self, stdout):         self.stdout = stdout       def write(self, s):         self.stdout.write(string.lower(s))   # redirect standard output (including the print statement) #

python标准库学习5 ---bisect — Array bisection algorithm

#coding=utf-8   import bisect   list=[1,2,3,4,6,7,8,9]   #假定list已经排序 print bisect.bisect_left(list,5)  #返回5应该插入的索引位置   print bisect.bisect_right(list, 5)   print bisect.bisect(list,5)   bisect.insort_left(list, 5, 0, len(list)) print list   bisect.in

Python标准库的学习准备

原文:Python标准库的学习准备 作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢!   Python标准库是Python强大的动力所在,我们已经在前文中有所介绍.由于标准库所涉及的应用很广,所以需要学习一定的背景知识.   硬件原理 这一部份需要了解内存,CPU,磁盘存储以及IO的功能和性能,了解计算机工作的流程,了解指令的概念.这些内容基础而重要. Python标准库的一部份是为了提高系统的性能(比如mmap),所以有必要了

Python标准库——走马观花

原文:Python标准库--走马观花 作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢!   Python的一大好处在于它有一套很有用的标准库(standard library).标准库是随着Python一起安装在你的电脑中的,是Python的一部分 (当然也有特殊情况.有些场合会因为系统安全性的要求,不使用全部的标准库,比如说Google App Engine).   利用已有的类(class)和函数(function)进行开发

Python标准库07 信号 (signal包,部分os包)

原文:Python标准库07 信号 (signal包,部分os包) 作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢!   在了解了Linux的信号基础之后,Python标准库中的signal包就很容易学习和理解.signal包负责在Python程序内部处理信号,典型的操作包括预设信号处理函数,暂停并等待信号,以及定时发出SIGALRM等.要注意,signal包主要是针对UNIX平台(比如Linux, MAC OS),而Windo

Python标准库09 当前进程信息 (部分os包)

原文:Python标准库09 当前进程信息 (部分os包)  作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢!   我们在Linux的概念与体系,多次提及进程的重要性.Python的os包中有查询和修改进程信息的函数.学习Python的这些工具也有助于理解Linux体系.   进程信息 os包中相关函数如下: uname() 返回操作系统相关信息.类似于Linux上的uname命令. umask() 设置该进程创建文件时的权限m