2

假设我的模板中有以下内容:

% if not mydict['somekey'] is UNDEFINED:
    ${mydict['somekey'][0]['hellothere']}</td></tr>
% endif    

我的问题是上面的内容不能像mydict['somekey']数组一样正常工作,但它可能是空的。我希望能够检查以确保是否mydict['somekey']已定义,我可以添加检查以确保 1)列表大小大于 0(从模板内部)或者其中是否mydict['somekey']包含元素,以便我可以打印出mydict['somekey'][0]['hellothere']可用的内容。

我必须做什么?我不断收到:

IndexError: list index out of range

与上述

4

1 回答 1

1

PEP 8建议:

对于序列(字符串、列表、元组),使用空序列为假的事实。

所以真的你不需要检查长度,只需像这样检查它:

% if mydict.get('somekey'):
    ${mydict['somekey'][0]['hellothere']}</td></tr>
% endif
于 2012-11-27T23:21:28.803 回答