In [2]:
x = [1, 2, 3]
y = [4, 5, 6]
z = [10, 12, 15, 17]
zip(x, y, z)
Out[2]:
In [3]:
a = [1, 2, 3, 4, 5]
b = [2, 2, 10, 1, 1]
for pair in zip(a,b):
print max(pair)
In [4]:
# each iteration of a element here, which would be a tuple generated by
# zip(), gets evaluated with max() in order to return a single, large value.
map(lambda pair: max(pair), zip(a,b))
Out[4]:
In [18]:
def switcharoo(d1, d2):
dout = {}
for k1, v2 in zip(d1, d2.itervalues()): #this zip creates the list of tuple ahead of time, and then iterates over it
dout[k1] = v2
return dout
In [19]:
dic1 = {'a':10, 'b':20}
dic2 = {'c':-20, 'd':-10}
switcharoo(dic1, dic2)
Out[19]:
In [32]:
'''
todos:
1. wtf is sentinel = object() for? is it a common code design pattern
2. why the * usage in parameter? is there reference/value aka, pointer, passing in python?
3. wtf is the yield reserved word do
'''
def zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
sentinel = object()
iterators = [iter(it) for it in iterables]
while iterators:
result = []
for it in iterators:
elem = next(it, sentinel)
if elem is sentinel:
return
result.append(elem)
yield tuple(result)
In [21]:
l = ['a', 'b', 'c']
count = 0
for item in l:
print count
print item
count += 1
In [22]:
for count,item in enumerate(l):
print count, item
In [33]:
'''
Functionally equivalent def for enumerate built-in
'''
def enumerate(sequence, start=0):
n = start
for elem in sequence:
yield n, elem
n += 1
In [23]:
'''
Very simply: all() checks that all members of a list evalue to True whereas
any() check that at least 1 evaluates to true
'''
l_bool = [True, False, True, True]
any(l_bool)
Out[23]:
In [24]:
all(l_bool)
Out[24]:
In [30]:
is_weekend = True
is_vacation = False
is_before_noon = True
snooze_alarm_requirements = [is_weekend, is_vacation, is_before_noon]
if any(snooze_alarm_requirements):
print("Snooze the alarm, it's too early")
if all(snooze_alarm_requirements):
print("Come back later, ain't no body got time for this")
else:
print("Really wished is was before noon, on a saturday on my vacation")
In [34]:
def all(iterable):
for element in iterable:
if not element:
return False
return True
def any(iterable):
for element in iterable:
if element:
return True
return False
In [ ]: