繁体   English   中英

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

[英]Check if any entries in a list ends with a specified string

所以,让我说我想找到以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)

regtester.com上的示例

endswith是一个字符串对象的方法。 您无法应用于字符串列表,并希望它可以神奇地应用于每个元素。 但是,你可以使用列表理解:

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

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

以下工作,但让我们调用列表myList:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM