我必须找到一个列表与另一个列表之间的区别。
但是这种寻找差异的过程使我每次跑步时的输出完全随机化。
下面是我的脚本
getALL = ["apple","ball","cat","dog","eagle"] // initial list
Sourcee = ["eagle", "ball"]
diff = list(set(getALL) - set(Sourcee))
for items in diff:
print(items)
有什么方法可以使diff
列表的顺序与getALL
相同?
我想要这样的输出:
apple
cat
dog
答案 0 :(得分:5)
只需列表理解即可。 (可选)将Sourcee
转换为set
会使其更快
>>> source_set = set(Sourcee)
>>> [e for e in getALL if e not in source_set]
['apple', 'cat', 'dog']
答案 1 :(得分:3)
设置操作不保留顺序。但是,您可以通过检查原始列表中的顺序来重建差异列表。这适用于任何任意顺序。如果原始列表包含重复项,则会使事情复杂化。
getALL = ["apple","ball","cat","dog","eagle"] # initial list
Sourcee = ["eagle", "ball"]
diff = list(set(getALL) - set(Sourcee))
original_order_diff = [x for x in getALL if x in diff]
print(original_order_diff)
答案 2 :(得分:2)
使用sorted
:
diff = list(set(getALL) - set(Source))
for items in sorted(diff, key=getALL.index):
print(items)
甚至:
print('\n'.join([i for i in getALL if i not in Source]))
并且:
print(*[i for i in getALL if i not in Source], sep='\n')
将是最短的解决方案。
它们全部输出:
apple
cat
dog