Skip to content

Instantly share code, notes, and snippets.

View poros's full-sized avatar

Antonio Uccio Verardi poros

View GitHub Profile
@poros
poros / zip.py
Created October 4, 2015 15:02
Loop over two collections
n = min(len(names), len(colors))
for i in range(n):
print names[i], colors[i]
for names, color in zip(names, colors):
print name, color
#collections.izip is the iterator version
@poros
poros / enumerate.py
Created October 4, 2015 14:55
Loop over a collection and indexes
for i in range(len(colors)):
print i, colors[i]
for i, colors in enumerate(colors):
print i, colors
# retuns enumerate object, not a list
@poros
poros / nested_list_comprehensions.py
Created October 4, 2015 14:47
Nested list comprehensions
matrix = [[1,2,3]] * 4
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
# FLATTEN THE MATRIX
flatten = []
for row in matrix:
for i in range(3):
flatten.append(row[i])
[row[i] for row in matrix for i in range(3)]
@poros
poros / comprehension.py
Created October 4, 2015 14:09
List/dict/set comprehensions
[x**2 for x in (2,4,6)]
{x: x**2 for x in (2, 4, 6)}
{x for x in 'abracadabra' if x not in 'abc'}
@poros
poros / try_except_else_finally.py
Created October 4, 2015 14:04
Complete exception handling
try:
f = open(filename, 'r')
except IOError as e:
print 'cannot open ', filename
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except:
log.exception("Unexpected error")
# print "Unexpected error:", sys.exc_info()[0]
raise
else:
@poros
poros / in_find_string.py
Created October 4, 2015 13:45
Find a substring is in a string
'lmnop' in 'abcdefghijklmnopqrstuvwxyz'
index = 'python'.find('on') # 4
@poros
poros / bool.py
Created October 4, 2015 13:36
Function testing a condition
if x % 2 == 0:
return True
return False
bool(x % 2 == 0)
@poros
poros / all.py
Created October 4, 2015 13:33
Check if every elements satisfies a condition
for x in numbers:
if x % 2 != 0:
return False
return True
all(x % 2 == 0 for x in numbers)
# it's a generator, stops at the first occurrence
@poros
poros / any.py
Created October 4, 2015 13:31
Check if at least one element satisfies a condition
for x in numbers:
if x % 2 == 0:
return True
return False
any(x % 2 == 0 for x in numbers)
# it's a generator, stops at the first occurrence
@poros
poros / izip_dictionary.py
Created October 4, 2015 13:21
Construct dictionary from pairs
dict(izip(keys, values))
# reuses the same tuple!