我目前正在使用 Python3 开发一个项目,并且需要实现此类代码,我在其中使用了一个 API 来传递具有限制计数的项目,并且需要找出已添加的最新项目。
我确定一定有更 Pythonic 的方式,但想不出任何方式。如果有类似的重复问题,请告诉我,因为我找不到。
list1 = ["d", "e", "f", "g", "h", "i", "j"] # items requested before
list2 = ["a", "b", "c", "d", "e", "f", "g"] # items requested now
for index, item in enumerate(list2):
if item is list1[0]:
print(list2[:index])
break
更新:
我在这些列表中有数千个项目,并且 list2 中的大部分与 list1 中的项目重复。我需要更有效的方法来处理这些差异。
请您参考如下方法:
您可以使用list2.index() 找到list1 的第一项在list2 中的索引:
list1 = ["d", "e", "f", "g", "h", "i", "j"] # items requested before
list2 = ["a", "b", "c", "d", "e", "f", "g"] # items requested now
print(list2[:list2.index(list1[0])])
以下部分代码
list2.index(list1[0])
将有效地找到 list1 中第一个元素的 list2 中的第一个索引。从算法的角度来看,这与手动实现的 python 循环一样高效,但在实践中效率更高,因为循环是 native 实现的,而不是在 python 中实现的。然后,您可以使用它从 list2 中取出一部分,就像您在自己的解决方案中所做的那样。
