#enumerate 的使用
def out(seq):
for i,item in enumerate(seq):
print(i,item)
out(['小明','小名','小铭'])
# 字典推导式
L1 = ['username','password','name','work']
L2 = ['admin','123456','xin yue','engineer']
d = {i:j for i,j in zip(L1,L2)}
print(d)
# 集合生成式
L1 = ['username','password','name','work']
L2 = ['admin','123456','xin yue','engineer']
L2.extend(L1)
S = {i for i in L2}
print(S)
from collections import OrderedDict
def from_key_val_list(value):
"""获取一个对象并测试它是否可以表示为字典,除非它不能这样表示,否则返回OrderedDict"""
if value is None:
return None
if isinstance(value,(str,bytes,int,bool)):
raise ValueError('cannot encode objects that are not 2-tuple!')
return OrderedDict(value)
# test
print(from_key_val_list([('key', 'val')])) # OrderedDict([('key', 'val')])
print(from_key_val_list({'key': 'val'})) # OrderedDict([('key', 'val')])
print(from_key_val_list('string')) # ValueError: cannot encode objects that are not 2-tuples
from collections.abc import Mapping
def to_key_val_list(value):
"""获取一个对象并测试它是否可以表示为字典. 如果可以的话,返回一个元组列表"""
if value is None:
return None
if isinstance(value,(str,bytes,int,bool)):
raise ValueError('cannot encode objects that are not 2-tuple!')
if isinstance(value,Mapping):
value = value.items()
return list(value)
# test
print(to_key_val_list([('key', 'val')])) # [('key', 'val')]
print(to_key_val_list({'key': 'val'})) # [('key', 'val')]
print(to_key_val_list('string')) # ValueError: cannot encode objects that are not 2-tuples.
def guess_filename(obj):
""" Tries to guess the filename of the given object."""
name = getattr(obj,'name',None)
if (name and isinstance(name,(str, bytes)) and
name[0] != '<' and name[-1] != '>'):
return os.path.basename(name)
def urldefragauth(url):
""" Given a url remove the fragment and the authentication part."""
scheme, netloc, path, params, query, fragment = urlparse(url)
if not netloc:
netloc, path = path, netloc
netloc = netloc.rsplit('@', 1)[-1]
return urlunparse((scheme, netloc, path, params, query, ''))
from urllib.parse import urlparse,unquote
def get_auth_from_url(url):
"""Given a url with authentication components, extract them into a tuple of username,password"""
parsed = urlparse(url)
try:
auth = (unquote(parsed.username), unquote(parsed.password))
except (AttributeError, TypeError):
auth = ('','')
return auth
# test
url='http://admin:123456@127.0.0.1:8000'
print(get_auth_from_url(url))
from urllib.parse import urlparse,urlunparse
def prepend_scheme_if_needed(url, new_scheme):
"""
Given a URL that may or may not have a scheme, prepend the given scheme.
Does not replace a present scheme with the one provided as an argument.
"""
scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)
# urlparse is a finicky beast, and sometimes decides that there isn't a
# netloc present. Assume that it's being over-cautious, and switch netloc
# and path if urlparse decided there was no netloc.
if not netloc:
netloc, path = path, netloc
return urlunparse((scheme, netloc, path, params, query, fragment))
网友评论