为什么我无法执行此操作?我有2个以下的列表,嵌套和大小不等。我了解到我需要将列表转换为集合(hashable)然后执行比较,但我没有得到比较的输出(比如获取公共元素) 我试过下面的方法
list1 = [[u'i2_instance_floating_ip_association'], [u'i1_v1_instance_volume_attach']]
list2 = [[u'i2_instance_floating_ip_association', u'i2_v1_instance_volume_attach'], [u'i1_instance_floating_ip_association', u'i1_v1_instance_volume_attach']]
list1 = map(tuple, list1)
list2 = map(tuple, list2)
print(set(list1) & set(list2))
提供输出set()
或
for item in list1:
if item in list2:
print(item)
什么都没有
fin = [i for i in list1 if i in list2]
print("fin", fin)
给出fin []
答案 0 :(得分:1)
问题在于嵌套。你必须一直工作到元素。 例如:
for item in list1:
for list2_item in list2:
if item[0] in list2_item:
print(item)
输出:
['i2_instance_floating_ip_association']
['i1_v1_instance_volume_attach']
另一种方法是首先展平两个列表并将它们转换为集合:
flat1 = set(x[0] for x in list1)
flat2 = set(y for x in list2 for y in x)
print(flat1 & flat2)
输出:
{'i1_v1_instance_volume_attach', 'i2_instance_floating_ip_association'}
添加一些打印件以进行调试并了解会发生什么:
for item in list1:
print('item', item)
for list2_item in list2:
print('list2_item', list2_item)
if item[0] in list2_item:
print(' found', item[0], 'in', list2_item)
else:
print(' did not find', item[0], 'in', list2_item)
输出:
item ['i2_instance_floating_ip_association']
list2_item ['i2_instance_floating_ip_association', 'i2_v1_instance_volume_attach']
found i2_instance_floating_ip_association in ['i2_instance_floating_ip_association', 'i2_v1_instance_volume_attach']
list2_item ['i1_instance_floating_ip_association', 'i1_v1_instance_volume_attach']
did not find i2_instance_floating_ip_association in ['i1_instance_floating_ip_association', 'i1_v1_instance_volume_attach']
item ['i1_v1_instance_volume_attach']
list2_item ['i2_instance_floating_ip_association', 'i2_v1_instance_volume_attach']
did not find i1_v1_instance_volume_attach in ['i2_instance_floating_ip_association', 'i2_v1_instance_volume_attach']
list2_item ['i1_instance_floating_ip_association', 'i1_v1_instance_volume_attach']
found i1_v1_instance_volume_attach in ['i1_instance_floating_ip_association', 'i1_v1_instance_volume_attach']