Как найти объект из списка

Я использовал следующую программу для создания списка городов, полученных с веб-сайта. Теперь я хочу найти название города (аргумент) из списка, который я создал. Как это сделать?

Другими словами, как мне найти объект из списка? Я пробовал: listOfCities.find (city), я получил ошибку, поскольку атрибут find не был найден.

def weatherNow (city):
  import urllib
  connection = urllib.urlopen("http://weather.canoe.ca/Weather/World.html")
  weather = connection.read()
  connection.close()
  cityLoc = weather.find('class="weatherred"')
  cityEnd = weather.find("</a>", cityLoc)
  if city != -1:
    listOfCities = []
    while cityLoc != -1:
      cityNames = weather[cityLoc+19:cityEnd-1]
      listOfCities.append(cityNames)
      cityLoc = weather.find('class="weatherred"', cityLoc+1)
      cityEnd = weather.find("</a>", cityLoc)

  print listOfCities

Ответ 1

Чтобы проверить, находится ли city в listOfCities:

if city in listOfCities:
   # city is in the list

Чтобы найти его индекс в списке:

 i = listOfCities.index(city)

Он поднимает IndexError, если город не находится в listOfCities.

Вы можете использовать HTMLParser для синтаксического анализа html вместо регулярных выражений.

Полный пример

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import cgi

try:
    from html.parser import HTMLParser
except ImportError: # Python 2
    from HTMLParser import HTMLParser

try:
    from urllib.request import urlopen
except ImportError: # Python 2
    from urllib2 import urlopen

class CitiesParser(HTMLParser):
    """Extract city list from html."""
    def __init__(self, html):
        HTMLParser.__init__(self)
        self.cities = []
        self.incity = None
        self.feed(html)

    def handle_starttag(self, tag, attrs):
        self.incity = tag == 'a' and ('class', 'weatherred') in attrs
    def handle_endtag(self, tag):
        self.incity = False
    def handle_data(self, data):
        if self.incity:
            self.cities.append(data.strip())

# download and parse city list
response = urlopen("http://weather.canoe.ca/Weather/World.html")
_, params = cgi.parse_header(response.headers.get('Content-Type', ''))
html = response.read().decode(params['charset'])

# find city
cities = CitiesParser(html).cities
for city in ['Ar Riyāḍ', 'Riyadh']:
    if city in cities:
        print("%s is found" % (city,))
        print("the index is %d" % (cities.index(city),))
        break
    else:
        print("%r is not found" % (city,))