python 有用的python片段
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 有用的python片段相关的知识,希望对你有一定的参考价值。
##############################################
# Compare 2 dicts except some keys
def compare_dict(d1, d2, ignore):
for k in d1:
if k in ignore:
continue
try:
if d1[k] != d2[k]:
return False
except KeyError:
return False
return True
d1 = {'price': 1000.0, 'position': 'long', 'action': 'hold', 'warning': ''}
d2 = {'price': 1001.0, 'position': '', 'action': 'hold', 'warning': ''}
d3 = {'price': 1002.0, 'position': 'long', 'action': 'hold', 'warning': ''}
print(compare_dict(d1, d2, ['price']))
print(compare_dict(d2, d3, ['price']))
print(compare_dict(d1, d3, ['price']))
##############################################
# Convert a dictionary containing unicode string, non string into a json loadable object
def convert_dict_to_json(data, convert_unicode_to_string=True):
if isinstance(data, basestring):
return str(data)
elif isinstance(data, unicode):
if convert_unicode_to_string:
return data.encode('utf-8')
else:
return data
elif isinstance(data, collections.Mapping):
return dict(map(convert_dict_to_json, data.iteritems()))
elif isinstance(data, collections.Iterable):
return type(data)(map(convert_dict_to_json, data))
else:
return str(data)
##############################################
# Check if a key is in a dict
if myKey in dict:
do_some_work
else:
pass
# Option 2 - try exception
try:
do_some_work(dict[myKey])
except KeyError:
pass
##############################################
# String format
>>> "{:0>2}".format("1") # Works for both numbers and strings.
'01'
>>> "{:02}".format(1) # Only works for numbers.
'01'
##############################################
# Connect to HSQLDB
import jaydebeapi
conn = jaydebeapi.connect("org.hsqldb.jdbcDriver",
"jdbc:hsqldb:hsql://localhost:9000/db",
["SA", ""],
"/home/user_id/hsqldb-2.4.0/hsqldb/lib/hsqldb.jar",)
curs = conn.cursor()
query = """
SELECT *
FROM test
WHERE id = ?
"""
curs.execute(query, (some_id))
print curs.fetchall()
curs.close()
conn.close()
以上是关于python 有用的python片段的主要内容,如果未能解决你的问题,请参考以下文章
python 有用的python片段
python 机器学习有用的代码片段
python 有用的熊猫片段
python 有用的熊猫片段
python 有用的熊猫片段
python 有用的熊猫片段