Python 累加条件逻辑

Posted

技术标签:

【中文标题】Python 累加条件逻辑【英文标题】:Python accumulative conditional logic 【发布时间】:2012-05-11 13:35:36 【问题描述】:

我正在为以下问题的逻辑而苦苦挣扎,我知道即使我掌握了逻辑,我也可能会笨拙地实现它,所以任何建议都会很棒。

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

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

【问题讨论】:

【参考方案1】:

与其尝试在一个宏功能中完成,不如将其分解为更小的步骤。

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')

【讨论】:

【参考方案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

【讨论】:

我也从你的帖子中学到了很多,虽然我只能标记一个答案。非常感谢。

以上是关于Python 累加条件逻辑的主要内容,如果未能解决你的问题,请参考以下文章

学习Python之路:逻辑运算符

python逻辑与循环方式

python 逻辑运算符

4. python逻辑语句

要注意Python逻辑运算符与C/C++逻辑运算符的不同(逻辑与逻辑或逻辑非)用Python的if条件语句为示例

逻辑运算 (Python 3.4) - 有没有办法简化长条件语句?