Logical Error in Python script for comparing two lists

僤鯓⒐⒋嵵緔 提交于 2020-01-06 20:23:51

问题


I need to compare a configuration list(req_config) with a pre-existing(masterList) list.

I am getting some logical Error, as code is working fine for some configs and giving false output for other configs. Kindly help.

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

Expected Output:

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

Current output:

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:


The best practise is to normalize the inputs in some form, for example in this case, you may use str.lower() to convert the mixed case characters to lowercase characters and then perform comparison:

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


来源:https://stackoverflow.com/questions/33128109/logical-error-in-python-script-for-comparing-two-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!