drinks = ["coffee", "tea", "milk", "water"]
for drink in drinks:
print("thirsty for", drink)
#thirsty for coffee
#thirsty for tea
#thirsty for milk
#thirsty for water
drinks = ["coffee", "tea", "milk", "water"]
for index, drink in enumerate(drinks):
print("Item {} is {}".format(index, drink))
#Item 0 is coffee
#Item 1 is tea
#Item 2 is milk
#Item 3 is water
# deduplicate a list *fast*
print(set(["ham", "eggs", "bacon", "ham"]))
# {'bacon', 'eggs', 'ham'}
# compare lists to find differences/similarities
# {} without "key":"value" pairs makes a set
menu = {"pancakes", "ham", "eggs", "bacon"}
new_menu = {"coffee", "ham", "eggs", "bacon", "bagels"}
new_items = new_menu.difference(menu)
print("Try our new", ", ".join(new_items))
# Try our new bagels, coffee
discontinued_items = menu.difference(new_menu)
print("Sorry, we no longer have", ", ".join(discontinued_items))
# Sorry, we no longer have pancakes
old_items = new_menu.intersection(menu)
print("Or get the same old", ", ".join(old_items))
# Or get the same old eggs, bacon, ham
full_menu = new_menu.union(menu)
print("At one time or another, we've served:", ", ".join(full_menu))
# At one time or another, we've served: coffee, ham, pancakes, bagels, bacon, eggs
LightObject = namedtuple('LightObject', ['shortname', 'otherprop'])
m = LightObject()
m.shortname = 'athing'
> Traceback (most recent call last):
> AttributeError: can't set attribute
LightObject = namedtuple('LightObject', ['shortname', 'otherprop'])
n = LightObject(shortname='something', otherprop='something else')
n.shortname
# something
collections.defaultdict
login_times = {}
for t in logins:
if login_times.get(t.username, None):
login_times[t.username].append(t.datetime)
else:
login_times[t.username] = [t.datetime]
login_times = collections.defaultdict(list) for t in logins: login_times[t.username].append(t.datetime)
from datetime import datetime
class Event(object):
def __init__(self, t=None):
if t is None:
self.time = datetime.now()
else:
self.time = t
events = collections.defaultdict(Event)
for e in user_events:
print(events[e.name].time)
normal_dict = {
'a': {
'b': {
'c': {
'd': {
'e': 'really really nested dict'
}
}
}
}
}
from addict import Dict
addicted = Dict()
addicted.a.b.c.d.e = 'really really nested'
print(addicted)
# {'a': {'b': {'c': {'d': {'e': 'really really nested'}}}}}
from collections import defaultdict default = defaultdict(dict) default['a']['b']['c']['d']['e'] = 'really really nested dict' # fails
try: # get API data data = db.find(id='foo') # may raise exception # manipulate the data db.add(data) # save it again db.commit() # may raise exception except Exception: # log the failure db.rollback() db.close()
try:
# get API data
data = db.find(id='foo')
# may raise exception
except Exception:
# log the failure and bail out
log.warn("Could not retrieve FOO")
return
# manipulate the data
db.add(data)
try:
db.commit()
# may raise exception
except Exception:
log.warn("Failure committing transaction, rolling back")
db.rollback()
else:
log.info("Saved the new FOO")
finally:
db.close()
try:
# attempt to acquire a resource
db.commit()
except Exception:
# If it fails, clean up anything left behind
log.warn("Failure committing transaction, rolling back")
db.rollback()
else:
# If it works, perform actions
# In this case, we just log success
log.info("Saved the new FOO")
finally:
# Clean up
db.close()
# Program complete
db = db_library.connect("fakesql://")
# as a function
commit_or_rollback(db)
# context manager
with transaction("fakesql://") as db:
# retrieve data here
# modify data here
class DatabaseTransaction(object):
def __init__(self, connection_info):
self.conn = db_library.connect(connection_info)
def __enter__(self):
return self.conn
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
self.conn.rollback()
try:
self.conn.commit()
except Exception:
self.conn.rollback()
finally:
self.conn.close()
# context manager
with DatabaseTransaction("fakesql://") as db:
# retrieve data here
# modify data here
def my_generator(v):
yield 'first ' + v
yield 'second ' + v
yield 'third ' + v
print(my_generator('thing'))
# <generator object my_generator at 0x....>
for value in my_generator('thing'):
print value
# first thing
# second thing
# third thing
gen = my_generator('thing')
next(gen)
# 'first thing'
next(gen)
# 'second thing'
next(gen)
# 'third thing'
next(gen)
# raises StopIteration exception
def fib_generator():
a = 0
b = 1
while True:
yield a
a, b = b, a + b
min = 10000
for number in fib_generator():
if number > min:
print(number, "is the first fibonacci number over", min)
break
GET http://scream-about-food.com/search?q=coffee
{
"results": [
{"name": "Coffee Spot",
"screams": 99
},
{"name": "Corner Coffee",
"screams": 403
},
{"name": "Coffee Moose",
"screams": 31
},
{...}
]
"more": true,
"_next": "http://scream-about-food.com/search?q=coffee?p=2"
}
import requests
api_url = "http://scream-about-food.com/search?q={term}"
def infinite_search(term):
url = api_url.format(term)
while True:
data = requests.get(url).json()
for place in data['results']:
yield place
# end if we've gone through all the results
if not data['more']: break
url = data['_next']
# pass a number to start at as the second argument if you don't want
# zero-indexing
for number, result in enumerate(infinite_search("coffee"), 1):
if result['name'] == "The Coffee Stain":
print("Our restaurant, The Coffee Stain is number ", number)
return
print("Our restaurant, The Coffee Stain didnt't show up at all! :(")
for result in infinite_search("coffee"):
if result['name'] == "The Coffee Stain":
print("Our restaurant, The Coffee Stain is number ", result['number'])
return
print("Our restaurant, The Coffee Stain didn't show up at all! :(")
Divided Over Division
print "hello"
# Python 2
print("hello")
# Python 3
from __future__ import print_function
print("hello")
# Python 2
print("hello")
# Python 3
print(1 / 3) # Python 2 # 0 print(1 / 3) # Python 3 # 0.3333333333333333 print(1 // 3) # Python 3 # 0
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有