Patrick
Patrick

Reputation: 2544

How to search a sub-string in elements of a list speedily?

I have some data like this:

data = [
    'HTTP/1.1 200 OK',
    'CACHE-CONTROL: max-age=1810',
    'DATE: Wed, 14 May 2014 12:15:19 GMT',
    'EXT:',
    'LOCATION: http://192.168.94.57:9000/DeviceDescription.xml',
    'SERVER: Windows NT/5.0, UPnP/1.0, pvConnect UPnP SDK/1.0',
    'ST: uuid:7076436f-6e65-1063-8074-78542e239ff5',
    'USN: uuid:7076436f-6e65-1063-8074-78542e239ff5',
    'Content-Length: 0',
    '',
    ''
]

from which I have to extract the ".xml" link.

My code is:

for element in data:
    if 'LOCATION' in element:
        xmllink = element.split(': ').[1]

It's taking too much time - how can I make this more speedy?

Upvotes: 0

Views: 36

Answers (1)

schesis
schesis

Reputation: 59258

With the usual caveats that

  1. Premature optimization is the root of all evil, and
  2. Python is built for comfort, not for speed ...

This ought to be a little faster:

for element in data:
    if element.startswith('LOCATION: '):
        xmllink = element[10:]  # len('LOCATION: ') == 10
        break

... but, like your code, it'll break if there isn't exactly one space after LOCATION:, and in many other situations that may or may not occur with your data.

Upvotes: 2

Related Questions