简体   繁体   中英

How to check if list contains any item from list in python

i am trying to check and print if following list contains specific string or substring using Python,

This is my input

[
  [
    "SessionTimeOut: Request reach to it's max time. {'VwasKXznXVVzYU6iAAAB': None} were registered but ['192.168.2.2', '192.168.2.3'] were expected."
  ],
  [
    "CommonException: element with 'id' was not found"
  ],
  [
    "JenkisException: Element missing because service was down"
  ]
]

Now i want to get the output string if it contains

"SessionTimeOut: Request reach to it's max time.

I am able to check it this way

print('SessionTimeOut: Request reach to it's max time.' in str(response['data']))

It returns True but i also want that complete string I am able to print that as response['data'][0][0] this is not a good idea.

I want to printout the complete string dynamically which contains that text, How can i achieve this. Thank you.

How about using any built-in and itertools.chain :

from itertools import chain

data = [
    [
        "SessionTimeOut: Request reach to it's max time. {'VwasKXznXVVzYU6iAAAB': None} were registered but ['192.168.2.2', '192.168.2.3'] were expected."
    ],
    [
        "CommonException: element with 'id' was not found"
    ],
    [
        "JenkisException: Element missing because service was down"
    ]
]

string_to_search = "SessionTimeOut: Request reach to it's max time."
print(any(string_to_search in obj for obj in chain(*data)))

If you want to return that specific string:

print([obj for obj in chain(*data) if string_to_search in obj][0])

Ouptut:

True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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