【问题标题】:Logical Error in Python script for comparing two lists用于比较两个列表的 Python 脚本中的逻辑错误
【发布时间】:2015-10-14 14:28:12
【问题描述】:

我需要将配置列表 (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

【问题讨论】:

  • conservativeRasEn != ConservativeRasEn(通知信大小写)
  • 谢谢。我可以得到错误。我可以问你,如何使我的比较不区分大小写。这是实际的要求。

标签: python string-comparison


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-30
    • 2010-12-08
    • 2020-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    相关资源
    最近更新 更多