Python 查找一个列表中不以另一个列表中的项目开头的项目

Python 查找一个列表中不以另一个列表中的项目开头的项目,python,list,for-loop,Python,List,For Loop,我正在尝试编写一个代码,查找一个列表中的每个实例,这些实例不是以另一个列表中的项目开头的 我正在尝试这个: list1 = ['1234', '2345', '3456', '4567'] list2 = ['1', '2'] for x in list1: for y in list2: if not x.startswith(y): print(x) 但它返回的是: 1234 2345 3456 3456 4567 4567 这让我感到困

我正在尝试编写一个代码,查找一个列表中的每个实例,这些实例不是以另一个列表中的项目开头的

我正在尝试这个:

list1 = ['1234', '2345', '3456', '4567']
list2 = ['1', '2']

for x in list1:
    for y in list2:
        if not x.startswith(y):
            print(x)
但它返回的是:

1234
2345
3456
3456
4567
4567

这让我感到困惑,因为如果我删除“not”,它可以在列表1中找到以列表2中的项目开头的项目。如何编写实现目标的代码?

这是因为如果值不是以1或2开头,代码将打印输出

试试这个:

list1 = ['1234', '2345', '3456', '4567'] 
list2 = ['1', '2'] 
for x in list1:
    if not any([x.startswith(y) for y in list2]):
            print(x)

尝试一个for/else循环。只有在循环没有中断的情况下,else才会执行

list1 = ['1234', '2345', '3456', '4567']
list2 = ['1', '2']

for x in list1:
    for y in list2:
        if x.startswith(y):
            break
    else:
        print(x)

这是一个纯粹合乎逻辑的问题。我不知道如何用英语清楚地描述它,所以这里有一张桌子。最后一列中的每个
True
表示
x
将在您的代码中打印。我希望它能澄清你的代码是如何工作的

for x in list1:
    for y in list2:
        print(x, y, not x.startswith(y))
解决方案是将
列表2
全部循环,并使用或检查结果:

你可以试试这个

list1 = ['1234', '2345', '3456', '4567'] 
list2 = ['1', '2']
print( *[x for x in list1 if all([x[:len(l)]!=l for l in list2])],sep="\n")

我建议使用调试器并逐步运行代码。基本上,您需要知道
all
any
之间的区别@ACan 4个输入有6个输出,怎么可能?这个问题的答案是您的解决方案。相关:
for x in list1:
    if not any(x.startswith(y) for y in list2):
        print(x)
3456
4567
list1 = ['1234', '2345', '3456', '4567'] 
list2 = ['1', '2']
print( *[x for x in list1 if all([x[:len(l)]!=l for l in list2])],sep="\n")