Skip to main content
 首页 » 编程设计

python之检查列表最后几个位置的每个元素是否在另一个列表中

2024年12月31日7softidea

我环顾四周,没有找到询问列表中最后一项而不是整个列表的问题。 如果列表中的最后一项在另一个列表中,我正在尝试做某事。

pile = [2,6,9] 
 
another = [1,5,6,5,4,1,6,7] 
 
if another[-1:-4:-1] in pile:  #if one of the last 3 items in 'another' are in the list 'pile' then print yes 
 
    print("yes") 
else: 
 
    print("no") 

我尝试使用切片,但我认为这不是正确的方法,顺便说一句,我是新手。 我试图让程序获得列表“另一个”中的最后 3 个项目,如果最后 3 个元素之一在另一个列表“堆”中,则打印是。 在这种情况下,6 在 'another[-1:-4:-1]' 和 'pile' 中,但我不知道如何在代码中编写它以使其工作

我使用这个基本示例来尝试解释它,但在我正在编写的程序中,新项目被附加到列表“另一个”上,因此最后项目的索引将发生变化。我只需要检查最后的项目,而不是其余的项目。

请您参考如下方法:

您可以使用 sets,它允许测试交集:

if set(pile).intersection(set(another[-3:])): 
    print("yes") 
else: 
    print("no")