如果List1
中的元素等于List2
中的项目,我正尝试将值扩展到列表。我使用extend而不是append因为extend假设合并两个列表。相反,它似乎是嵌套列表。
删除y[1],y[2]
周围的括号会产生:
SyntaxError: Generator expression must be parenthesized if not sole argument
List1 = [['value1','value2','Value3'],['value4','value5','value6']]
List2 = [['option1','option2','value2'],['option3','option4','value5']]
for x in List1:
x.extend([y[1],y[2]] for y in List2 if y[2] == x[1])
print List1
我的输出:
[['value1', 'value2', 'Value3', ['option2', 'value2']], ['value4', 'value5', 'value6', ['option4', 'value5']]]
期望的输出:
[['value1', 'value2', 'Value3', 'option2', 'value2'], ['value4', 'value5', 'value6', 'option4', 'value5']]
答案 0 :(得分:1)
作为[[y[1],y[2]] for y in List2 if y[2] == x[1]]
返回列表列表
>>> List1 = [['value1','value2','Value3'],['value4','value5','value6']]
>>> List2 = [['option1','option2','value2'],['option3','option4','value5']]
>>> for x in List1:
... [[y[1],y[2]] for y in List2 if y[2] == x[1]]
...
[['option2', 'value2']]
[['option4', 'value5']]
所以从列表中获取第一项以扩展x
>>> List1 = [['value1','value2','Value3'],['value4','value5','value6']]
>>> List2 = [['option1','option2','value2'],['option3','option4','value5']]
>>> for x in List1:
... x.extend([[y[1],y[2]] for y in List2 if y[2] == x[1]][0])
...
>>> List1
[['value1', 'value2', 'Value3', 'option2', 'value2'], ['value4', 'value5', 'value6', 'option4', 'value5']]
>>>
Python初学者 逐行扩展上面的代码。
代码:
>>> List1 = [['value1','value2','Value3'],['value4','value5','value6']]
>>> List2 = [['option1','option2','value2'],['option3','option4','value5']]
>>>
>>> for x in List1:
... for y in List2:
... if y[2]==x[1]:
... print "In if value:", [y[1],y[2]]
... x.extend([y[1],y[2]])
...
In if value: ['option2', 'value2']
In if value: ['option4', 'value5']
>>> List1
[['value1', 'value2', 'Value3', 'option2', 'value2'], ['value4', 'value5', 'value6', 'option4', 'value5']]
>>>
答案 1 :(得分:1)
使用itertools.chain.from_iterable
将迭代器/列表的迭代器/列表展平为迭代器/列表,然后将其传递给.extend(
。这适用于以下情况:
([y[1],y[2]] for y in List2 if y[2] == x[1])
有多少场比赛。示例输入只有一个,但最好是期望更合理。参见:
>>> import itertools
>>> List1 = [['value1','value2','Value3'],['value4','value5','value6']]
>>> List2 = [['option1','option2','value2'],['option3','option4','value5']]
>>>
>>> for x in List1:
... x.extend(itertools.chain.from_iterable([y[1],y[2]] for y in List2 if y[2] == x[1]))
...
>>> print List1
[['value1', 'value2', 'Value3', 'option2', 'value2'], ['value4', 'value5', 'value6', 'option4', 'value5']]