【问题标题】:List returned by SafeConfigParser is [''], but shows a len() of 1SafeConfigParser 返回的列表是 [''],但显示 len() 为 1
【发布时间】:2014-10-10 15:26:10
【问题描述】:

我有一个类似的配置文件:

[Expected Response]
    GlobalResponse:

    UniqueResponse:
        1221

我想要做的是,如果 GlobalResponse 为空,那么我们依赖于设置 UniqueResponse

subConfigParser = ConfigParser.SafeConfigParser(allow_no_value=True)   
subConfigParser.read(os.path.join(relativeRunPath, 'veri.cfg'))
commands = subConfigParser.get('Command List', 'commands').strip().split("\n")
expectedResponse = subConfigParser.get('Expected Response', 'GlobalResponse').strip().split("\n")
print expectedResponse
print len(expectedResponse)
if not expectedResponse:
    expectedResponse = subConfigParser.get('Expected Response', 'UniqueResponse').strip().split("\n")
    print "Size of unique: {}".format(len(expectedResponse))
    if len(expectedResponse) != len(commands):
        sys.exit(1)

但是,这是我得到的输出:

['']   # print expectedResponse
1      # print len(expectedResponse)

我错过了什么?

【问题讨论】:

  • 您期待什么? [''] 是一个包含一项的列表,所以它的长度自然是 1。
  • 您是否对为什么要返回[''] 感到困惑?或者为什么len(['']) 等于1?后者是预期行为。
  • 进一步的 kindall 评论 [] 是一个 len 为 0 的列表
  • 嗯,好吧,我不知道[''] == len of 1。对不起,我对 Python 很陌生。所以我想这是一个问题,当我期望它什么都不返回时,ConfigParser 返回一些东西。

标签: python list configparser


【解决方案1】:

这种行为是意料之中的。

[''] 是一个包含'' 的列表对象,'' 是一个空字符串对象。即使'' 为空,它仍然是一个对象,因此算作列表中的一个元素。因此,len 返回 1,因为列表只有一项。

下面是一个更好解释的演示:

>>> len([]) # Length of an empty list
0
>>> # Length of a list that contains 1 string object which happens to be empty.
>>> len([''])
1
>>> # Length of a list that contains 2 string objects which happen to be empty.
>>> len(['', ''])
2
>>>

也许你打算写:

if not expectedResponse or not expectedResponse[0]:

如果expectedResponse 为空[] 或其第一个元素为空[''],则此 if 语句的条件将通过。

注意如果expectedResponse总是包含一个元素,你应该写:

if not expectedResponse[0]:

这将测试expectedResponse 的第一个(唯一)元素是否为空。

【讨论】:

    猜你喜欢
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 2014-02-23
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多