【发布时间】:2017-12-24 03:32:20
【问题描述】:
您好,我想比较两个不同长度的列表,并打印一个排序表,其中包含每个表中缺少的项目。我部分能够完成此操作并打印 list_2 中缺少的值。但我也无法从 list_2 中打印 list_1 中缺少的值,即字母“z”。如何执行此操作以获得以下所需的输出?
list_1 = ['a', 'b', 'c', 'd', 'e', 'f']
list_2 = ['b', 'c', 'f', 'z']
table_format = '{:<10} {:<10}'
print(table_format.format('list_1', 'list_2'))
print('-' * 20)
for x in list_1:
for y in list_2:
if x in y:
print(table_format.format(x, y))
break
else:
print(table_format.format(x,'Missing'))
电流输出:
list_1 list_2
--------------------
a Missing
b b
c c
d Missing
e Missing
f f
期望的输出:
list_1 list_2
--------------------
a Missing
b b
c c
d Missing
e Missing
f f
Missing z
【问题讨论】:
-
你考虑过使用
set吗?试试set(list_2) - set(list_1) -
这确实提供了缺失值,但不确定在 for 循环期间如何制作表格的那部分。