我有两个列表,我想与列表理解相结合,但不断收到IndexError: List index out of range
错误:
List1 = [[u'Case1', u'DP1', u'Configuration1', u'New'], [u'Case2', u'DP2', u'Configuration2', u'New']]
List2 = [[u'DP1', u'EB1', u'Typ1'], [u'DP2', u'EB2', u'Type2'], [u'DP3', u'EB3', u'Type2']]
for key, item in enumerate(List2):
List2[key] = [item[0],[x for x in List1 if (x[1] == item[0] and x[2] == 'Configuration1')][0][3]]
print List2
我尝试添加else None
,但后来获得SyntaxError: invalid syntax
例外:
List2[key] = [item[0],[x for x in List1 if (x[1] == item[0] and x[2] == 'Configuration1') else None][0][3]]
我的预期输出是:
[[u'DP1', u'New'], [u'DP2', None], [u'DP3',None]]
答案 0 :(得分:2)
List1
中的第二个列表在索引2处没有值'Configuration1'
,因此列表推导为空。索引空列表会产生索引错误:
>>> List1 = [[u'Case1', u'DP1', u'Configuration1', u'New'], [u'Case2', u'DP2', u'Configuration2', u'New']]
>>> List2 = [[u'DP1', u'EB1', u'Typ1'], [u'DP2', u'EB2', u'Type2'], [u'DP3', u'EB3', u'Type2']]
>>> item = List2[1]
>>> [x for x in List1 if x[1] == item[0] and x[2] == 'Configuration1']
[]
>>> [x for x in List1 if x[1] == item[0] and x[2] == 'Configuration1'][0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
您的更改语法无效;您无法在列表推导else
过滤器中使用if
:
>>> [x for x in List1 if (x[1] == item[0] and x[2] == 'Configuration1') else None]
File "<stdin>", line 1
[x for x in List1 if (x[1] == item[0] and x[2] == 'Configuration1') else None]
^
SyntaxError: invalid syntax
那是因为if
部分不是条件表达式,而是列表理解语法的一部分。 if
测试过滤元素。您在列表推导的左侧表达式中使用条件表达式,但这样做没有任何意义。
如果您想查找匹配的数据,则应将List1
转换为字典:
configuration_data = {(entry[1], entry[2]): entry[3] for entry in List1}
这会将索引1和2处的项目映射到索引3处的元素,因此您只需使用字典查找来填充List2
的新列表对象:
List2 = [[item[0], configuration_data.get((item[0], 'Configuration1'), None)]
for item in List2]
此列表理解与您尝试使用枚举的for
循环实现的效果相同;生成具有匹配配置数据的新列表:
>>> List1 = [[u'Case1', u'DP1', u'Configuration1', u'New'], [u'Case2', u'DP2', u'Configuration2', u'New']]
>>> List2 = [[u'DP1', u'EB1', u'Typ1'], [u'DP2', u'EB2', u'Type2'], [u'DP3', u'EB3', u'Type2']]
>>> configuration_data = {(entry[1], entry[2]): entry[3] for entry in List1}
>>> [[item[0], configuration_data.get((item[0], 'Configuration1'), None)] for item in List2]
[[u'DP1', u'New'], [u'DP2', None], [u'DP3', None]]
答案 1 :(得分:0)
列表推导的if语法不允许&#34; else&#34;。 此列表理解会生成您期望的输出:
[item[0],[x if (x[1] == item[0] and x[2] == 'Configuration1') else [None] * 4 for x in List1][0][3]]
我刚刚将if..else交换到列表推导的前面并更改了None
以获取列表,因此当您使用[3]
对其进行索引时,它不会抛出错误。