使用 endswith() 检查一个列表中的字符串是否以另一个列表中的字符串结尾?

Use endswith() to check if a string in one list ends with a string from another list?

我需要检查列表中的项目是否列在另一个列表中字符串的末尾,最好通过某种方式使用 endswith() 但我不确定如何仅使用此方法解决它而不是让它取决于其他列表的长度等..

对于单个列表,这非常有效:

mylist = ["item 1 a", "item 2 a", "item 3 b"]

for item in mylist:
    if item.endswith("a"):
        print(f"{item} ends with 'a'")
    else:
        print(f"{item} ends with 'b'")

# Output: 
# item 1 a ends with 'a'
# item 2 a ends with 'a'
# item 3 b ends with 'b'

但假设我有 2 个列表,我不确定如何检查一个列表中的列表项是否以另一个列表中的选项之一结尾。由于 endswith() 只是 returns 真或假,我完全知道下面的代码是错误的,但它更像是一种展示我希望它如何工作的方式:

mylist = ["item 1", "item 2", "item 3"]
newlist = ["added item 1", "added item 3"]

for item in mylist:
    if item.endswith(item) in newlist:
# Wont work because the return is a boolean
# value, just an example of what I'm looking for'
        print(f"newlist has {item} added")
    else:
        print(f"newlist still waiting for {item}")

我知道还有其他方法可以获得相同的结果,但是有没有什么方法可以做到这一点而不需要使用正则表达式或另一个列表来存储不同的字符串并仅基于 endswith()?

您的示例代码有点令人困惑,但如果您想检查 mylist 中的哪些项目是 newlist 中任何字符串的后缀,以下应该有效:

mylist = ["item 1", "item 2", "item 3"]
newlist = ["added item 1", "added item 3"]

for item in mylist:
    found = False
    
    for newitem in newlist:
       if newitem.endswith(item):
           found = True
           break

    if found:
       print(f"newlist has {item} added")
    else:
       print(f"newlist still waiting for {item}")

这段代码的输出如下,我猜这就是你想要的:

newlist has item 1 added
newlist still waiting for item 2
newlist has item 3 added

如果我理解正确,这应该是解决方案

mylist = ["item 1", "item 2", "item 3"]
newlist = ["added item 1", "added item 3"]

for item in mylist:
    for other_item in newlist:
        if other_item.endswith(item):
            print(f"newlist has {item} added")
            break
        
        print(f"newlist still waiting for {item}")

控制台输出是这样的

newlist has item 1 added
newlist still waiting for item 2
newlist still waiting for item 2
newlist still waiting for item 3
newlist has item 3 added

如果您不希望第 2 项的输出重复,您可以在第二个 for 循环找到该项目的情况下添加一个变量,如果没有,您可以编写该消息。类似于:

mylist = ["item 1", "item 2", "item 3"]
newlist = ["added item 1", "added item 3"]

for item in mylist:
    found = False
    for other_item in newlist:
        if other_item.endswith(item):
            print(f"newlist has {item} added")
            found = True
            break

    if found is not True:
        print(f"newlist still waiting for {item}")

这让你:

newlist has item 1 added
newlist still waiting for item 2
newlist has item 3 added

看起来您只需要嵌套循环来检查列表 1 中的每个项目和列表 2 中的每个项目。

mylist = ["item 1", "item 2", "item 3"]
newlist = ["added item 1", "added item 3"]

for item in newlist:
  for item1 in mylist:
    if item1.endswith(item):
        print(f"newlist has {item} added")
    else:
        print(f"newlist still waiting for {item}")