在 Python 中对两个列表进行相减和相加而不改变它们的顺序
如果我有列表 [68,31,93,35,10]
(所有数字都会不同)和列表 [93,0,22,10,99,33, 21,9]
(同样,所有数字都会不同,但可能与其他列表重叠),我需要能够准确地得到[68,31,93,35,10,0,22,99,33,21,9]
,其中第二个列表附加到第一个列表且不重复。我还需要能够准确获取 [68,31,35]
,其中第一个列表已删除第二个列表中的所有重复项。输出的顺序应始终与输入的顺序相同。我该怎么办? (如果简单的话,一个衬垫就很好了。)
If I have the list [68,31,93,35,10]
(all the numbers will be different) and the list [93,0,22,10,99,33,21,9]
(again, all the numbers will be different, but may overlap the other list), I need to be able to get exactly [68,31,93,35,10,0,22,99,33,21,9]
, where the second list is appended to the first list without duplicates. I also need to be able to get exactly [68,31,35]
where the first list has all duplicates in the second list removed. The output always should be the same order as the input. How do I go about this? (A one liner would be nice if it were simple.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
编辑:对于长列表,您不想进行所有这些列表查找。这是另外两个食谱:
联合:
差异:
EDIT: for long lists, you don't want to do all those list lookups. Here are two other recipes:
union:
difference:
假设输入
l1
和l2
,您可以使用以下方法计算它们的有序并集:要获得有序差值 l1 - l2,请写入
或者,使用列表推导式:
如果您这样做对于非常大的列表(其中性能是一个问题),构造一个
set
以加快查找速度:Assuming inputs
l1
andl2
, you can calculate their ordered union with:To get the ordered difference l1 - l2, write
Alternatively, use list comprehensions:
If you're doing this with very large list (where performance is an issue), construct a
set
for faster lookup:也许你可以使用
OrderedSet
Maybe you could use an
OrderedSet
如此定义前两个列表后,
这是第一个问题的单行解决方案,
以及第二个问题的单行解决方案,
After defining the first two lists as such,
Here is the one-line solution to the first problem,
And the one-liner to the second problem,