我有一个包含类似内容的文件
#comment
#comment
不是评论#comment
#comment
不是评论
我试图逐行读取文件,只捕获不以#开头的行.我的代码/正则表达式出了什么问题?
import re
def read_file():
pattern = re.compile("^(?<!# ).*")
with open('list') as f:
for line in f:
print pattern.findall(line)
Run Code Online (Sandbox Code Playgroud)
原始代码捕获所有内容而不是预期.
鉴于字典:
sample = {
'123': 'Foo',
'456': 'Bar',
'789': 'Hello',
'-111': 'World'
}
Run Code Online (Sandbox Code Playgroud)
从字典中获取最接近(或更少)密钥的最有效方法(方法和/或数据结构)是什么?
注意:
1.即使key是一个字符串,比较也应该是数字.
2.键可以是"否定的".
例:
get_nearest_less_element(sample, '456') # returns 'Bar'
get_nearest_less_element(sample, '235') # returns 'Foo'
get_nearest_less_element(sample, '455') # returns 'Foo'
get_nearest_less_element(sample, '999') # returns 'Hello'
get_nearest_less_element(sample, '0') # returns 'World'
get_nearest_less_element(sample, '-110') # returns 'World'
get_nearest_less_element(sample, '-999') # should return an error since it is beyond the lower bound
Run Code Online (Sandbox Code Playgroud)
附加问题:
给定相同的数据集,一个sorted OrderedDict或一个List of Tuples或任何其他python数据结构是更好的方法吗?
我有一本字典,其中包含一个日期和一个时间列表(以字符串形式)。
input = {
'2016-02-11': [
u'30m',
u'2h 30m',
u'1h',
u'2h',
u'30m',
u'1h',
u'30m',
u'1h',
u'45m'
],
'2016-01-27': [
u'1d'
],
'2016-01-28': [
u'30m',
u'5h',
u'30m',
u'1h',
u'45m'
],
'2016-01-29': [
u'30m',
u'6h 30m',
u'45m'
],
'2016-02-09': [
u'30m',
u'15m',
u'4h',
u'15m',
u'2h',
u'45m'
]
}
Run Code Online (Sandbox Code Playgroud)
如何在列表中每次添加?这样新字典看起来像这样:
output = {
'2016-02-11': [
'9h 45m'
],
'2016-01-27': [
'8h'
],
'2016-01-28': [
'7h 45m'
],
'2016-01-29': [
'7h 45m'
],
'2016-02-09': [
'7h 45m'
]
}
Run Code Online (Sandbox Code Playgroud)
一些注意事项:
I have a function inside a module that creates an argparse:
def get_options(prog_version='1.0', prog_usage='', misc_opts=None):
options = [] if misc_opts is None else misc_opts
parser = ArgumentParser(usage=prog_usage) if prog_usage else ArgumentParser()
parser.add_argument('-v', '--version', action='version', version='%(prog)s {}'.format(prog_version))
parser.add_argument('-c', '--config', dest='config', required=True, help='the path to the configuration file')
for option in options:
if 'option' in option and 'destination' in option:
parser.add_argument(option['option'],
dest=option.get('destination', ''),
default=option.get('default', ''),
help=option.get('description', ''),
action=option.get('action', 'store'))
return parser.parse_args()
Run Code Online (Sandbox Code Playgroud)
A sample myapp.py would be:
my_options = [
{
"option": …Run Code Online (Sandbox Code Playgroud)