Python 检查列表中的任何条目是否以指定字符串结尾

Python 检查列表中的任何条目是否以指定字符串结尾,python,list,Python,List,假设我想找到以foo结尾的条目 你会认为你做了如下事情: results=list.endswith(“foo”) 然后打印出以字符串foo 我该怎么做 for entry in list: if entry.endswith("foo"): print(entry) 或使用列表: for entry in [entry for entry in list if entry.endswith("foo")]: print(entry) 是一种用于字符串对象的方

假设我想找到以
foo
结尾的条目

你会认为你做了如下事情:

results=list.endswith(“foo”)

然后打印出以字符串
foo

我该怎么做

for entry in list:
    if entry.endswith("foo"):
        print(entry)
或使用列表:

for entry in [entry for entry in list if entry.endswith("foo")]:
    print(entry)
是一种用于字符串对象的方法。您不能应用于字符串列表,而期望它神奇地应用于每个元素。不过,您可以使用列表理解:

results = [string for string in list if string.endswith("foo")]

这将返回以“foo”结尾的字符串列表。然后,您可以检查它是否包含任何元素。

以下操作有效,但让我们将列表称为myList:

result = [x for x in myList if x.endswith('foo')]

我个人不这么认为。您想检查
是否有任何
(提示!)有那个结尾,还是让那个结尾?你有没有试过把那些做过的列一个清单?测试它的长度?检查列表中是否有以
foo
结尾的条目,然后打印结果。检查结果是否为真或假。说真的,你试过什么?