Python累积条件逻辑

时间:2012-05-02 04:16:50

标签: python if-statement logic

我正在努力解决下面问题的逻辑,我知道即使我把逻辑钉在了一起,我也可能会笨拙地实现它,所以任何建议都会很棒。

我有一个代表文件的字典:

the_file = {'Filename':'x:\\myfile.doc','Modified':datetime(2012,2,3),'Size':32412}

我有一个过滤器列表,我想过滤文件字典以确定匹配。

filters = [
    {'Key':'Filename','Criteria':'Contains','Value':'my'},
    {'Key':'Filename','Criteria':'Does not end with','Value':'-M.txt'},
    {'Key':'Modified','Criteria':'After','Value':datetime(2012,1,1)}
    ]

我最好尝试创建一个函数来执行此操作(不起作用):

def is_asset(the_file, filters):
match = False
for f in filters:
    if f['Key'] == u'Filename':
        if f['Criteria'] == u'Contains':
            if f['Value'] in the_file['Filename']:
                match = True
        elif f['Criteria'] == u'Starts with':
            if the_file['Filename'].startswith(f['Value']):
                match = True
        elif f['Criteria'] == u'Ends with':
            if the_file['Filename'].endswith(f['Value']):
                match = True
        elif not f['Criteria'] == u'Does not end with':
            if the_file['Filename'].endswith(f['Value']):
                match = False
        elif f['Criteria'] == u'Equals':
            if os.path.basename(the_file['Filename']) == f['Value']:
                match = True
        elif f['Criteria'] == u'Does not contain':
            if f['Value'] in the_file['Filename']:
                match = False
    elif f['Key'] == u'Modified':
        mtime = int(os.path.getmtime(the_file['Filename']))
        if f['Criteria'] == u'Before':
            if f['Value'] > datetime.fromtimestamp(mtime):
                the_file['Modified'] = mtime
                match = True
        elif f['Criteria'] == u'After':
            if f['Value'] < datetime.fromtimestamp(mtime):
                the_file['Modified'] = mtime
                match = True
    elif f['Key'] == u'Size':
        size = long(os.path.getsize(the_file['Filename']))
        if f['Criteria'] == u'Bigger':
            if f['Value'] < size:
                the_file['Size'] = size
                match = True
            elif f['Value'] > size:
                the_file['Size'] = size
                match = True
    if match:
        return the_file

2 个答案:

答案 0 :(得分:4)

不要试图在一个宏功能中进行,而是将其分解为更小的步骤。

filenamecondmap = {
  u'Contains': operator.contains,
  u'Does not end with': lambda x, y: not x.endswith(y),
   ...
}

 ...

condmap = {
  u'Filename': filenamecondmap,
  u'Modified': modifiedcondmap,
   ...
}

然后走结构直到你有条件,然后执行它。

condmap[u'Filename'][u'Contains'](thefile['Filename'], 'my')

答案 1 :(得分:2)

您可以简单地将功能用作“标准”。这使得它变得更加简单,因为你不必编写一个很大的if-else梯形图。像这样:

def contains(value, sub):
    return sub in value

def after(value, dt):
    return value > dt

filters = [
    {'Key': 'FileName', 'Criteria': contains, 'Value': 'my'},
    {'Key': 'Modified', 'Criteria': after,  'Value': datetime(2012,1,1)}
]

for f in filters:
    if f['Criteria'](filename[f['Key']], f['Value']):
       return True