-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpythonBeauty.txt
More file actions
95 lines (73 loc) · 1.88 KB
/
pythonBeauty.txt
File metadata and controls
95 lines (73 loc) · 1.88 KB
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
** Looping backwards
-----------------------------------------
for i in range(len(a) - 1, -1, -1):
print a[i]
for blah in reversed(a):
print(blah)
-> The second one is faster
** Looping over a collection and indices
-----------------------------------------
for i in range(len(a)):
print i, '-->', a[i]
for i, blah in enumerate(a):
print i, '-->', blah
** Looping over two collections
-----------------------------------------
n = min(len(blahs1), len(blahs2))
for i in range(n):
print blahs1[i], '-->', blahs2[i]
for blah1, blah2 in zip(blahs1, blahs2):
print blah1, '-->', blah2
for blah1, blah2 in izip(blahs1, blahs2):
print blah1, '-->', blah2
** Looping in sorted order
-----------------------------------------
for color in sorted(colors):
print color
for color in sorted(color, reverse=True):
print color
** Custom sort order
-----------------------------------------
def compare_length(c1, c2):
if len(c1) < len(c2): return -1
if len(c1) > len(c2): return 1
return 0
print sorted(colors, cmp=compare_length)
print sorted(colors, key=len)
** Call a function until a sentinel value
-----------------------------------------
blocks = []
while True:
block = f.read(32)
if block == '':
break
blocks.append(block)
blocks = []
for block in iter(partial(f.read(32), ''):
blocks.append(block)
** Distinguishing multiple exit loops in python
-----------------------------------------
def find(seq, target):
found = False
for i, value in enumerate(seq):
if value == target:
found = True
break
if not found:
return -1
return 1
def find(seq, target):
for i, value in enumerate(seq):
if value == target:
break
else:
return -1
return
** Loop over dictioary keys and values
-----------------------------------------
for key in dic:
print key, '-->', dic[key]
for key, val in dic.items():
print key, '-->', val
for key, val in dic.iteritems():
print key, '-->', val1