如何在查找两个列表的差异时保持输出列表的顺序

2024-09-30 08:18:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我得找出一张单子和另一张单子的区别。你知道吗

但是这种寻找差异的过程在我每次运行时都会随机输出。你知道吗

下面是我的剧本

你知道吗

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

Tags: apple过程diffitems差异listcat单子
3条回答

只需要一个列表就行了。有选择地将Sourcee转换成set会使它更快

>>> source_set = set(Sourcee)
>>> [e for e in getALL if e not in source_set]
['apple', 'cat', 'dog']

set操作不保留顺序。但是,您可以通过检查原始列表中的顺序来重新构建diff列表。这适用于任意顺序。如果原始列表包含重复项,则会使问题复杂化。你知道吗

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)

使用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

相关问题 更多 >

    热门问题