简体   繁体   English

如何在python的List中找到字符串的一部分

[英]How can I find the part of string is in List in python

Let's say I have the following list 假设我有以下清单

List = ['Apple', 'Banana', 'Orange', 'Grapes']

From this I want to search Apple I have to use the following code 我要从中搜索Apple我必须使用以下代码

if 'Apple' in List: 
    print "Found"

But I want to search the string which contains 'App' what do I have to do? 但是我想搜索包含'App'的字符串,我该怎么做?

I can use For loop and if statement combined. 我可以使用For循环和if语句组合。

for items in List: 
    if 'App' in items: 
        print "Found"

But is there any other way to do this process? 但是还有其他方法可以执行此过程吗?

You can use map + any : 您可以使用map + any

lst = ['apple', 'banana']

if any(map(lambda x: 'app' in x.lower(), lst)):
    print "Found"

Slightly more pythonic: 稍微更pythonic:

lst = ['apple', 'banana']
if any(['app' in x.lower() for x in lst]):
    print "Found"

A slightly more optimized version using a generator (if the first element is "apple", it won't check the rest of the lst): 使用生成器进行了稍微优化的版本(如果第一个元素是“ apple”,它将不会检查其余的第一个元素):

generator = ('app' in x.lower() for x in lst)
if any(generator):
    print "Found"
if(True in ["app" in k for k in ["apple","orange","grapes"]]):
    print("woot")

Is more or less readable but does the same thing. 具有或多或少的可读性,但功能相同。

you could even make it a one liner, 你甚至可以把它做成一根

print "woot" if(True in ["app" in k for k in ["apple","orange","grapes"]]) else ""

If you're just looking for something more concise, the exact same logic can be written with a comprehension (in this case, a generator expression ) and the any function: 如果您只是在寻找更简洁的内容,可以使用理解 (在本例中为generator expression )和any函数编写完全相同的逻辑:

if any('App' in item for item in List):
    print "Found"

If it isn't obvious why this does almost the same thing as your existing code: 如果不太明显,为什么这样做与现有代码几乎相同:

If you expand the comprehension to an explicit for statement, it looks like this: 如果将理解扩展为显式的for语句,则如下所示:

for item in List:
    yield 'App' in item

Then, the any function iterates over each thing that got yield ed until one of them is true, or until it gets to the end and they were all false. 然后, any函数都会对获得yield每一件事进行迭代,直到其中之一为真,或者直到结果都为假为止。

So, the only difference is that instead of printing "Found" once for each time something was found, it just prints it once and then stops looking. 因此,唯一的区别是,每次发现某项内容时都不会打印一次"Found" ,而是只会打印一次,然后停止查找。


If you want something more efficient , you'd need to change your data structure. 如果您想要更有效的方法 ,则需要更改数据结构。 But I doubt that's an issue when you've only got 4 things in List . 但是我怀疑在List只有4件事时这是一个问题。

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

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