2014-10-10 26 views
-1

一個LEN()我有一個配置文件是這樣的:名單爲[「」],但顯示的1

[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) 

我缺少什麼?

+2

你期待什麼? '['']'是一個包含一個項目的列表,所以它的長度自然是1. – kindall 2014-10-10 15:30:19

+1

你爲什麼要得到'['']'你感到困惑嗎?或者爲什麼'len([''])'等於'1'?後者是預期的行爲。 – CoryKramer 2014-10-10 15:30:37

+1

進一步kindall的評論'[]'是一個列表與len 0 – 2014-10-10 15:30:48

回答

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]: 

該if-statment的狀況會通過,如果expectedResponse是空[]或如果其第一個元素爲空['']

注意,如果expectedResponse總是包含一個元素,你應該寫:

if not expectedResponse[0]: 

這是檢驗的expectedResponse第一個(只)元素爲空。