2 回答
TA贡献1789条经验 获得超10个赞
看来您在输入数据中使用括号时存在一些细微的不一致,我冒昧地纠正了这些不一致。完成此操作后,为了真正解决问题,我认为将第二个数组转换为字典以便于包含测试是有意义的。这给出:
from pprint import pprint
array_1 = [('Rabbits', [('/home/white', 'white rabbits'),
('/home/black', 'black rabbits'),
('/home/green', 'green rabbits')]),
('Cats', [('/ans/pink', 'pink cats'),
('/ans/purple', 'purple cats'),
('/home/grey', 'grey cats')]),
('Hippos', [('/home/red', 'red hippo')])]
array_2 = [('Rabbits', [('/home/black', 'black rabbits'),
('/home/green', 'green rabbits')]),
('Cats', [('/ans/pink', 'pink cats'),
('/home/grey', 'grey cats')]),
('Hippos', [])]
d = dict(array_2)
out = []
for species, tups in array_1:
lst = []
for tup in tups:
if tup in d[species]:
lst.append(tup + (True,))
else:
lst.append(tup + (False,))
out.append((species, lst))
pprint(out)
输出:
[('Rabbits',
[('/home/white', 'white rabbits', False),
('/home/black', 'black rabbits', True),
('/home/green', 'green rabbits', True)]),
('Cats',
[('/ans/pink', 'pink cats', True),
('/ans/purple', 'purple cats', False),
('/home/grey', 'grey cats', True)]),
('Hippos', [('/home/red', 'red hippo', False)])]
TA贡献1995条经验 获得超2个赞
第一个数组中有一些括号拼写错误,我已更正它们。
以下代码应该可以工作:
l1=[('Rabbits', [('/home/white', 'white rabbits'), ('/home/black', 'black rabbits'), ('/home/green', 'green rabbits')]), ('Cats', [('/ans/pink', 'pink cats'), ('/ans/purple', 'purple cats'), ('/home/grey', 'grey cats')]), ('Hippos', [('/home/red', 'red hippo')]), ]
l2=[('Rabbits', [('/home/black', 'black rabbits'), ('/home/green', 'green rabbits')]), ('Cats', [('/ans/pink', 'pink cats'), ('/home/grey', 'grey cats')]), ('Hippos', []) ]
m=[i[1][k] for i in l2 for k in range(len(i[1]))]
for i in range(len(l1)):
for k in range(len(l1[i][1])):
if l1[i][1][k] in m:
l1[i][1][k]+=(True,)
else:
l1[i][1][k]+=(False,)
print(l1)
添加回答
举报