用于比较两个列表的Python脚本中的逻辑错误

时间:2015-10-14 14:28:13

标签: python string-comparison

我需要将配置列表(req_config)与预先存在的(masterList)列表进行比较。

我得到一些逻辑错误,因为代码对于某些配置工作正常并且为其他配置提供错误输出。请帮助。

import re
masterList = ['MEMSize', 'conservativeRasEn', 'Height', 'multipleBatch', 'Width', 'dumpAllRegsAtFinish', 'ProtectCtl', 'isdumpEnabled','vh0', 'vw0','lEnable', 'WaveSize','maxLevel','pmVer', 'cSwitchEn', 'disablePreempt', 'disablePreemptInPass', 'ctxSwQueryEn', 'forceEnable', 'enableDebug', '5ErrEn', 'ErrorEn']
req_config = ['MEMSize', 'Height', 'Width', 'isdumpEnabled', 'vh0', 'vw0', 'lEnable', 'WaveSize', 'maxLevel', 'Information', 'ConservativeRasEn']

for config in req_config:
    if any(config in s for s in masterList):
        print "Config matching: ", config
    else:
        print "No match for: ", config

预期产出:

Config matching:  MEMSize
Config matching:  Height
Config matching:  Width
Config matching:  isdumpEnabled
Config matching:  vh0
Config matching:  vw0
Config matching:  lEnable
Config matching:  WaveSize
Config matching:  maxLevel
No match for:  Information
Config matching:  ConservativeRasEn

当前输出:

Config matching:  MEMSize
Config matching:  Height
Config matching:  Width
Config matching:  isdumpEnabled
Config matching:  vh0
Config matching:  vw0
Config matching:  lEnable
Config matching:  WaveSize
Config matching:  maxLevel
No match for:  Information
No match for:  ConservativeRasEn

1 个答案:

答案 0 :(得分:1)

最佳做法是以某种形式规范化输入,例如,在这种情况下,您可以使用str.lower()将混合大小写字符转换为小写字符,然后执行比较:

masterList = ['MEMSize', 'conservativeRasEn', 'Height', 'multipleBatch', 'Width', 'dumpAllRegsAtFinish', 'ProtectCtl', 'isdumpEnabled','vh0', 'vw0','lEnable', 'WaveSize','maxLevel','pmVer', 'cSwitchEn', 'disablePreempt', 'disablePreemptInPass', 'ctxSwQueryEn', 'forceEnable', 'enableDebug', '5ErrEn', 'ErrorEn']
req_config = ['MEMSize', 'Height', 'Width', 'isdumpEnabled', 'vh0', 'vw0', 'lEnable', 'WaveSize', 'maxLevel', 'Information', 'ConservativeRasEn']

masterList = map(str.lower, masterList)

for config in req_config:
    if config.lower() in masterList:
        print "Config matching: ", config
    else:
        print "No match for: ", config