为什么此列表索引超出范围

时间:2019-05-11 07:43:29

标签: python

我有一个Python程序,在以下代码行中崩溃,错误为list index out of range

        split_choices_translated = map(unicode.strip, [value for key, value in obj.items() if 'choice_set_' in key][0].split(';'))

这些是发生这种情况时使用的变量和值:

Variable    Value
item_id     u'usage'

item_type   u'radiobutton'

key         'definition'

obj         {'category': u'how_use_words',
 'choices__choice_set': u'not yet; sometimes; often',
 'definition': u'does your child ever talk about past events or people who are not present?',
 'itemID': u'item_681',
 'item_type': u'usage'}

object_group  <QuerySet [{'itemID': u'item_681', 'item_type': u'usage', 'choices__choice_set': u'not yet; sometimes; often', 'category': u'how_use_words', 'definition': u'does your child ever talk about past events or people who are not present?'}, {'itemID': u'item_682', 'item_type': u'usage', 'choices__choice_set': u'not yet; sometimes; often', 'category': u'how_use_words', 'definition': u"does your child ever talk about something that's going to happen in the future?"}, {'itemID': u'item_683', 'item_type': u'usage', 'choices__choice_set': u'not yet; sometimes; often', 'category': u'how_use_words', 'definition': u'does your child talk about objects that are not present?'}, {'itemID': u'item_684', 'item_type': u'usage', 'choices__choice_set': u'not yet; sometimes; often', 'category': u'how_use_words', 'definition': u'does your child understand if you ask for something that is not in the room?'}, {'itemID': u'item_685', 'item_type': u'usage', 'choices__choice_set': u'not yet; sometimes; often', 'category': u'how_use_words', 'definition': u'does your child ever pick up or point to an object and name an absent person to whom the object belongs?'}]>

prefilled_data   {}

raw_split_choices  [u'not yet', u'sometimes', u'often']

value   u'does your child ever talk about past events or people who are not present?'

我无法锻炼出问题所在

1 个答案:

答案 0 :(得分:1)

您的代码失败,因为条件列表理解中的测试:

if 'choice_set_' in key

永远不会true,因为您输入中的键都不包含choice_set_作为子字符串。因此,您的理解会返回一个空列表,但随后您尝试解决该列表中的第一项。由于没有第一项,因此会出现list index out of range错误。