问题
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