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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
|
#coding=utf-8
import copy
'''
文本类型: str //str("Hello World")
数值类型: int, float, compl ex // int(29) float(29.5) complex(1j)
序列类型: list, tuple, range // list(("apple", "banana", "cherry")) tuple(("apple", "banana", "cherry")) range(6)
映射类型: dict // dict(name="Bill", age=36)
集合类型: set, frozenset // set(("apple", "banana", "cherry")) frozenset(("apple", "banana", "cherry"))
布尔类型: bool // bool(5)
二进制类型: bytes, bytearray, memoryview // bytes(5) bytearray(5) memoryview(bytes(5))
'''
def testDataType():
print("================= testDataType ===============")
x = 27e4 # ===> 270000 float type
y = 15E2
z = -49.8e100
x = 2+3j
y = 7j
z = -7j
print(x, type(x))
print(y,type(y))
print(z,type(z))
# 数据类型检查可以用内置函数isinstance()实现
print(isinstance(x, (int, float))) # ===> False
# input param
# print("Enter your name:")
# x = raw_input()
# print("Hello ", x)
testDataType()
def testFunction():
print("================= testFunction ===============")
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
# 关键字参数 参数的顺序无关紧要
my_function(child1 = "Phoebe", child2 = "Jennifer", child3 = "Rory")
# 可变参数 函数定义的参数名称前添加 * 这样,函数将接收一个参数元组
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Phoebe", "Jennifer", "Rory")
# 关键字参数 函数定义的参数名称前添加 ** 这样,函数将接收一个参数dict
def person(name, age, **kw):
print('name:', name, 'age:', age, 'other:', kw)
person('Adam', 45, gender='M', job='Engineer') # ===>name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}
# 命名关键字参数 命名关键字参数需要一个特殊分隔符*,*后面的参数被视为命名关键字参数
# def person(name, age, *, city, job):
# print(name, age, city, job)
# person('Jack', 24, city='Beijing', job='Engineer') # ===>Jack 24 Beijing Engineer
# testFunction()
def testLambda():
# 匿名函数 lambda arguments : expression
print("================== testLambda ================")
x = lambda a : a + 10
print(x(5))
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
testLambda()
def testString():
# 所有字符串方法都返回新值。它们不会更改原始字符串。
print("================= testString ===============")
a = "Hello, World!"
print(a[1]) # ===>e str is an byte array
# 裁切
print(a[2:5]) # ===>llo 获取从位置 2 到位置 5(不包括)的字符
print(a[-5:-2]) # ===>orl 获取从位置 5 到位置 2(不包括)的字符,从字符串末尾开始计数
print(len(a)) # ===>13 字符串长度
print(" Hello, World! ".strip()) # ===>Hello, World! strip方法删除开头和结尾的空白字符
print(a.replace("World", "Kitty"), a) # ===>Hello, Kitty!
# in / not in 检查字符串中是否存在特定短语或字符(string is a list)
txt = "China is a great country"
x = "ina" in txt
print(x)
x = "ain" not in txt
print(x)
testString()
def testFormat():
print("================= testFormat ===============")
quantity = 3
itemno = 567
price = 49.951
myorder = "I want {} pieces of item {} for {:.2f} dollars." # {:.2f} 格式化为带有两位小数的数字
print(myorder.format(quantity, itemno, price))
myorder = "I want to pay {2:.3f} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
myorder = "I have a {carname}, it is a {model}." # 命名索引
print(myorder.format(carname = "Porsche", model = "911"))
print('Hi, %s, you have $%d.' % ('Michael', 1000000))
print('%2d-%02d' % (3, 1))
print('%.2f' % 3.1415926)
testFormat()
def testIsNotis():
print("================= testIsNotis ===============")
x = 2
y = 5
print(x ** y) # ===>32 same as 2*2*2*2*2
# is / is not
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x
print(x is z) # ===> True returns True because z is the same object as x
print(x is y) # ===> False returns False because x is not the same object as y, even if they have the same content
print(x is not y) # ===> True
print(x == y) # ===> True to demonstrate the difference betweeen "is" and "==": this comparison returns True because x is equal to y
# in / not in
print("banana" in x)# ===>True because a sequence with the value "banana" is in the list
testIsNotis()
"""
Python 集合(数组)
Python 编程语言中有四种集合数据类型:
列表[List]是一种有序和可更改的集合。允许重复的成员。列表用方括号编写,链表实现
元组(Tuple)是一种有序且不可更改的集合。允许重复的成员。元组用圆括号编写,元祖还有个特性,是只读的,定义后不可修改
集合{Set}是一个无序和无索引可更改的集合。没有重复的成员。集合用花括号编写,集合是无序的,因此您无法确定项目的显示顺序。
词典{Dictionary}是一个无序,可变和有索引的集合。没有重复的成员。字典用花括号编写,拥有键和值
有序或无序是指是否按照其添加的顺序来存储对象
"""
def testList():
print("=================== testList ==================")
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist, thislist[0], thislist[-1], len(thislist)) # 负索引表示从末尾开始,-1 表示最后一个项目
print(thislist[2:5]) # 从索引 2(包括)开始,到索引 5(不包括)
print(thislist[-3:-1]) # 从字符串末尾开始计数
L = list(range(100))
print(L[:10:2]) # ===>[0, 2, 4, 6, 8] 前10个数,每两个取一个
print(L[::5]) # ===>[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95] 所有数,每5个取一个
print(L[:]) # 原样复制一个list
for x in thislist:
print(x)
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
thislist.append("orange2")
print(thislist)
thislist.insert(1, "orange3")
print(thislist)
thislist.remove("orange3")
print(thislist)
thislist.pop()
print(thislist)
thislist.pop(1)
print(thislist)
del thislist[0]
print(thislist)
# thislist.clear()
# print(thislist)
# del thislist
# 列表生成式
print(list(range(5))) # ===> [0, 1, 2, 3, 4]
print([x * x for x in range(1, 11)]) # ===> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print([x * x for x in range(1, 11) if x % 2 == 0]) # ===> [4, 16, 36, 64, 100] 这里 if 是筛选条件,不能加 else
print([m + n for m in 'ABC' for n in 'XYZ']) # ===> ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
# 生成器 generator
L = [x * x for x in range(10)]
g = (x * x for x in range(10)) # 创建L和g的区别仅在于最外层的[]和(),L是一个list,而g是一个generator, generator保存的是算法
for n in g:
print(n) # 0 1 4 9 16 25 36 49 64 81
# enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身
for i, value in enumerate(['A', 'B', 'C']):
print(i, value)
# 0 A 1 B 2 C
for x, y in [(1, 1), (2, 4), (3, 9)]:
print(x, y)
# 1 1 2 4 3 9
def copyList():
print("---------------- copyList ----------------")
myList = list(("apple", "banana", "cherry"))
listA = copy.copy(myList) # this function should be add 'import copy' (python 2.7)
print(listA)
listB = list(myList)
print(listB)
def mergeList():
print("---------------- mergeList ----------------")
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
list1.extend(list2)
print(list1)
for x in list2:
list1.append(x)
print(list1)
testList()
copyList()
mergeList()
def testTuple():
print("=================== testTuple ==================")
# 和list集合最大的区别就是不能增删改
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango",)
print(thistuple, len(thistuple), thistuple[0], thistuple[-1], thistuple[2:5], thistuple[-3:-1])
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
# del thistuple
# print(thistuple) # 这会引发错误,因为元组已不存在。
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.count(5) # 返回指定值在元组中出现的次数
print(x)
x = thistuple.index(8) # 查找指定值第一次出现位置,如果未找到该值,index() 方法将引发异常。
print(x)
def updateTupleValue():
print("------------------ updateTupleValue ------------------")
thistuple = ("apple", "banana", "cherry")
# thistuple[0] = "apple0" ERROR 创建元组后,您将无法更改其值。元组是不可变的,或者也称为恒定的。
x = list(thistuple)
x[0] = "apple0"
thistuple = tuple(x)
for x in thistuple:
print(x)
t = ('a', 'b', ['A', 'B'])
t[2][0] = 'X'
t[2][1] = 'Y'
print(t) # ===> ('a', 'b', ['X', 'Y']) 表面上看,tuple的元素确实变了,但其实变的不是tuple的元素,而是list的元素,所以,tuple所谓的“不变”是说,tuple的每个元素,指向永远不变
def createSingleTuple():
# 如需创建仅包含一个项目的元组,您必须在该项目后添加一个逗号,否则 Python 无法将变量识别为元组。
thistuple = ("apple",)
print(type(thistuple))
# 不是元组
thistuple = ("apple")
print(type(thistuple))
def mergeTuple():
tuple1 = ("a", "b", "c")
tuple2 = tuple((1, 2, 3))
tuple3 = tuple1 + tuple2
print(tuple3, type(tuple3))
testTuple()
# updateTupleValue()
# createSingleTuple()
mergeTuple()
def testSet():
print("=================== testSet ==================")
# 和list集合最大的区别就是没有下标,无序唯一
# set 是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key
thisset = {"apple", "banana", "cherry"}
print(thisset, len(thisset))
if "apple" in thisset:
print("Yes, apple in this set")
for x in thisset:
print(x)
def addSet():
print("------------------ addSet ------------------")
thisset = set(("apple", "banana", "cherry"))
thisset.add("orange") # 要将一个项添加到集合,请使用 add() 方法
print(thisset)
thisset.update(["kiwi", "mango", "grapes"]) # 要向集合中添加多个项目,请使用 update() 方法
print(thisset)
def deleteSet():
print("------------------ deleteSet ------------------")
thisset = {"apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"}
print(thisset)
thisset.remove("banana") # 如果要删除的项目不存在,则 remove() 将引发错误。
print(thisset)
thisset.discard("apple")
print(thisset)
# 还可以使用 pop() 方法删除项目,但此方法将删除最后一项。请记住,set 是无序的
# 因此您不会知道被删除的是什么项目,pop() 方法的返回值是被删除的项目
x = thisset.pop()
print(x)
print(thisset)
thisset.clear() # clear() 方法清空集合
print(thisset)
# del thisset # del 彻底删除集合
def mergeSet():
print("------------------ mergeSet ------------------")
set1 = set(("a", "b", "c"))
set2 = {1, 2, 3}
set3 = set1.union(set2) # union() 方法返回一个新集合,其中包含两个集合中的所有项目
print(set3)
set1.update(set2) # update() 方法将 set2 中的项目插入 set1 中
print(set1)
# union() 和 update() 都将排除任何重复项
testSet()
# addSet()
# deleteSet()
mergeSet()
def testDict():
print("=================== testDict ==================")
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963,
}
print(thisdict, len(thisdict), thisdict["model"], thisdict.get("model"))
thisdict["year"] = 2020
print(thisdict)
for x in thisdict:
print(x, thisdict[x])
for x in thisdict.values():
print(x)
thisdict["color"] = "red"
for x, y in thisdict.items():
print(x, y)
if "model" in thisdict: # 检查字典中是否存在 "model",如果不存在,用 thisdict["model"] 会报错
print("Yes, 'model' is one of the keys in the thisdict dictionary")
print(thisdict.get("model")) # 不存在时返回 None 不会报错
print(thisdict.get("model", "default")) # 不存在时返回默认值 default
def deleteDict():
print("------------------ deleteDict -------------------")
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963,
"color": "red",
}
print(thisdict)
thisdict.pop("model")
print(thisdict)
thisdict.popitem() # popitem() 方法删除最后插入的项目(在 3.7 之前的版本中,删除随机项目)
print(thisdict)
del thisdict["year"] # del 关键字也可以完全删除字典 del thisdict
print(thisdict)
thisdict.clear() # clear() 关键字清空字典
print(thisdict)
def copyDict():
print("------------------ copyDict -------------------")
thisdict = dict(
brand = "Porsche",
model = "911",
year = 1963
)
print(thisdict)
mydict = thisdict.copy()
print(mydict)
mydict2 = dict(thisdict)
print(mydict2)
testDict()
deleteDict()
copyDict()
def testIfAndLoop():
print("=================== testIfAndLoop ==================")
a = 200
b = 66
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
if a > b: print("a is greater than b")
if a > b:
pass # if / for 语句不能为空,但是如果您处于某种原因写了无内容的 if 语句,请使用 pass 语句来避免错误
i = 1
while i < 6:
print(i)
i += 1
else: # 通过使用 else 语句,当条件不再成立时,我们可以运行一次代码块
print("i is no longer less than 6")
# range() 循环一组代码指定的次数
for x in range(10):
print(x)
else: # else 关键字指定循环结束时要执行的代码块
print("Finally finished!")
for x in range(3, 10): # 3 到 10(但不包括 10)
print(x)
for x in range(3, 50, 6): # 3 到 50 增量值 6
print(x)
from collections import Iterable
print(isinstance('abc', Iterable)) # ===>True 对象是否可迭代
print(isinstance([1,2,3], Iterable)) # ===>True
print(isinstance(123, Iterable)) # ===> False
# testIfAndLoop()
def prn_obj(obj):
print('\n'.join(['%s:%s' % item for item in obj.__dict__.items()]))
def testObject():
print("====================== testObject ===================")
class Person:
def __init__(self, name, age): # 每次使用类创建新对象时,都会自动调用 __init__() 函数
# self 参数是对类的当前实例的引用,用于访问属于该类的变量
# 它不必被命名为 self,您可以随意调用它,但它必须是类中任意函数的首个参数
# 比如此处 self 改成其他变量名,其他地方的 self 就要替换成对应的变量名
self.name = name
self.age = age
# 此处首个参数 self 改成其他名字也可以,比如 a.name
def printname(self):
print("Hello my name is " + self.name)
p = Person("Bill", 63)
p.printname()
# 继承 创建子类时将父类作为参数
class Student(Person):
def __init__(self, fname, lname): # 当您添加 __init__() 函数时,子类将不再继承父的 __init__() 函数
# 如需保持父的 __init__() 函数的继承,请添加对父的 __init__() 函数的调用
Person.__init__(self, lname, age=1)
self.firstName = fname
self.lastName = lname
def welcome(self):
print("Welcome", self.firstName, self.lastName, "to the class of")
# 如果您在子类中添加一个与父类中的函数同名的方法,则将覆盖父方法的继承
p = Student("Alex", "Qiu")
p.printname()
p.welcome()
# 迭代器
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
# 创建迭代器(要把对象/类创建为迭代器,必须为对象实现 __iter__() 和 __next__() 方法)
class MyNumbers:
def __iter__(self): # __iter__() 方法可以执行操作(初始化等),但必须始终返回迭代器对象本身
self.a = 1
return self
def next(self): # __next__() 方法也允许您执行操作,并且必须返回序列中的下一个项目
if self.a <= 10:
x = self.a
self.a += 1
return x
else:
raise StopIteration # 防止迭代永远进行,我们可以使用 StopIteration 语句
myclass = MyNumbers()
myiter = iter(myclass)
for x in range(5):
print(next(myiter))
prn_obj(p)
testObject()
def testGlobalAndModule():
print("============================ testGlobalAndModule =======================")
# global
x = 2 # 如果要在函数内部更改全局变量,也请使用 global 关键字
def myfunc():
# global x # global 关键字使变量成为全局变量
# x = 100
print(x)
myfunc()
print(x)
import mymodule as mm # 为 mymodule 创建别名 mm
mm.greeting("Alex")
print(mm.person["name"])
import platform
x = platform.system()
print(x)
print(dir(mm)) # dir() 函数可以列出模块中的所有函数名(或变量名)
# 可以使用 from 关键字选择仅从模块导入部件
from mymodule import person # 仅从模块导入 person 字典
print(person["age"])
# testGlobalAndModule()
def testDate():
print("============================ testDate =======================")
import datetime # Python 中的日期不是其自身的数据类型,可以导入名为 datetime 的模块,把日期视作日期对象进行处理
x = datetime.datetime.now()
print(x)
print(x.year, x.month, x.day, x.hour, x.minute, x.second, x.microsecond, x.now())
print(x.strftime("%Y-%m-%d %H:%M:%S %a / %c"))
x = datetime.datetime(2020, 4, 23)
print(x)
import time, datetime
now = datetime.datetime.now()
perHourTick = int(time.mktime(now.replace(minute=0, second=0,microsecond=0).timetuple()))
nextHoutTick = int(time.mktime(now.replace(hour=now.hour + 1, minute=0, second=0,microsecond=0).timetuple()))
nowTick = int(time.mktime(now.timetuple()))
print(perHourTick, nextHoutTick, nextHoutTick - perHourTick, nowTick)
import time
timeStamp = 1381419600
timeArray = time.localtime(timeStamp)
print(timeArray)
# testDate()
def testJson():
print("============================ testJson =======================")
import json
x = '{ "name":"Bill", "age":63, "city":"Seatle"}'
print(x, type(x))
# json --> dict
y = json.loads(x)
print(y, type(y))
x = {
"name": "Bill",
"age": 63,
"city": "Seatle"
}
# python(dict, list, tuple, string, int, float, True, False, None) --> json
y = json.dumps(x)
print(y, type(y))
# 格式化 json 结果
# indent 参数定义缩进数 separators 参数来更改默认分隔符(使用.和空格分隔每个对象,使用=和空格将键与值分开)
# sort_keys 参数来指定是否应对结果进行排序
y = json.dumps(x, indent=4, separators=(". ", " = "), sort_keys=True)
print(y)
# testJson()
def testTryExcept():
print("============================ testTryExcept =======================")
# myname = "Alex"
try: # 允许您测试代码块以查找错误
print(myname)
except NameError: # 许您处理错误
print("Variable myname is not defined")
# raise Exception("Sorry, myname undefined") # raise 关键字用于引发异常
except: # 可以根据需要定义任意数量的 exception 块,为特殊类型的错误执行特殊代码块
print("Something else went wrong")
else:
print("Nothing went wrong")
finally: # 允许您执行代码,无论 try 和 except 块的结果如何(这对于关闭对象并清理资源非常有用,比如关闭文件)
print("The 'try except' is finished")
# testTryExcept()
def testIo():
print("==================== testIO ====================")
f = open("demofile.txt", "rt")
# f = open("myfile.log", "w") # 如果不存在,则创建新文件
# print(f.read()) # 默认情况下,read() 方法返回整个文本
# print(f.read(5)) # 返回文件中的前五个字符
# print(f.readline()) # 读取文件中的一行
# 逐行遍历文件
for x in f:
print(x)
f.close()
f = open("demofile2.txt", "a") # "a" - 追加 - 会追加到文件的末尾 "w" - 写入 - 会覆盖任何已有的内容
f.write("Now the file has more content!")
f.close()
f = open("demofile2.txt", "r")
print(f.read())
def fileExist():
print("==================== fileExist ====================")
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt") # 删除文件
os.rmdir("myfolder") # 删除文件夹 只能删除空文件夹
else:
print("The file does not exist")
# testIo()
# fileExist()
def testMapReduceFilter():
print("================== testMapReduceFilter ===================")
# map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回
def f(x):
return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) # map()传入的第一个参数是f,即函数对象本身
list(r) # ===>[1, 4, 9, 16, 25, 36, 49, 64, 81] 由于结果r是一个Iterator,Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list
list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])) # ===>['1', '2', '3', '4', '5', '6', '7', '8', '9'] 把这个list所有数字转为字符串
# reduce()函数把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
# 其效果就是:reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
from functools import reduce
def add(x, y):
return x + y
reduce(add, [1, 3, 5, 7, 9]) # ===>25
def fn(x, y):
return x * 10 + y
reduce(fn, [1, 3, 5, 7, 9]) # ===>13579
def char2num(s):
digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
return digits[s]
reduce(fn, map(char2num, '13579')) # ===>13579
def str2int(s):
return reduce(lambda x, y: x * 10 + y, map(char2num, s))
# 和map()类似,filter()也接收一个函数和一个序列。
# 和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
def is_odd(n):
return n % 2 == 1
# filter()函数返回的是一个Iterator,也就是一个惰性序列,所以要强迫filter()完成计算结果,需要用list()函数获得所有结果并返回list。
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])) # ===>[1, 5, 9, 15] 删掉偶数,只保留奇数
def not_empty(s):
return s and s.strip()
list(filter(not_empty, ['A', '', 'B', None, 'C', ' '])) # ===>['A', 'B', 'C'] 把一个序列中的空字符串删掉
testMapReduceFilter()
def testSorted():
print("=================== testSorted ==================")
print(sorted([36, 5, -12, 9, -21])) # ===>[-21, -12, 5, 9, 36]
print(sorted([36, 5, -12, 9, -21], key=abs)) # ===>[5, 9, -12, -21, 36] key函数来实现自定义的排序,例如按绝对值大小排序
print(sorted(['bob', 'about', 'Zoo', 'Credit'])) # ===>['Credit', 'Zoo', 'about', 'bob']
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)) # ===>['about', 'bob', 'Credit', 'Zoo'] 先把字符串都变成大写,忽略大小写来比较两个字符串
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)) # ===>['Zoo', 'Credit', 'bob', 'about'] 要进行反向排序,可以传入第三个参数reverse=True
testSorted()
def lazy_sum(*args):
import traceback
# traceback.print_stack()
stack = traceback.format_stack()
print("Traceback (most recent call last):\n" + "".join(stack))
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
# f = lazy_sum(1, 3, 5, 7, 9)
# print(f)
################################
def debugtrace():
import traceback
stack = traceback.format_stack()
INFO("Traceback (most recent call last):\n" + "".join(stack))
def myLog(*args):
import json
INFO(json.dumps(args or {}))
def printObj(obj):
INFO('\n'.join(['%s:%s' % item for item in obj.__dict__.items()]))
################################
def log(*args):
import json
import sys
print(str(sys._getframe().f_lineno) + " hehe.")
print(json.dumps(args))
log({"a":1,"b":2}, 123, "45", [1, "a", "b"], ("aa", "bb"))
a = {"1001": 1, "1002": 1}
for k, v in a.iteritems():
log(k, v)
# 三目运算符
def operator3(a, b):
return a if a < b else b
print(operator3(1, 2), operator3(9, 8))
a = 30
if 10 <= a < 40:
print("10 <= a < 40")
d = {
10 : 10001,
20 : 10002,
30 : 10003,
}
for k in sorted(d.keys(), reverse=True):
print(k)
d = {
1 : [1, 2, 3],
2 : [4, 5, 6],
3 : [7, 8, 9],
5 : [0, 1, 2],
}
for a, b, c in d.values():
print(a, b, c)
def MaxLessEqual(n, lst):
v = [ i for i in lst if i <= n ]
print(v)
if len(v) > 0:
return max(v)
print(MaxLessEqual(4, d.keys()))
print(d.keys())
print(max(d.keys()))
a, b = 1, 2
print(a, b)
b, a = a, b
print(a, b)
ACTIVITYTIMES = [
(134, 0, "springraid_boss" ),
(174, 0, "dragonboatreward" ),
]
for k, t, v in ACTIVITYTIMES:
print(k, t, v)
|