python - 如何从列表中查找对象

标签 python list find

我使用以下程序创建从网站获取的城市列表。现在我想从我创建的列表中查找城市名称(参数)。我该怎么做?

换句话说,如何从列表中查找对象?我尝试了: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

最佳答案

检查city是否在listOfCities中:

if city in listOfCities:
   # city is in the list

要在列表中查找其索引:

 i = listOfCities.index(city)

如果城市不在listOfCities中,则会引发IndexError

您可以使用 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,))

关于python - 如何从列表中查找对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13517527/

相关文章:

python - 如何使用 Python 获取游标对象的值

python - 获取二维数组中最近的坐标

python - 如何将列表转换为 csv 中的列?

list - Haskell中的子字符串

regex - Notepad++,搜索之间有通配符的字符串。除非(角色)出现在

linux - 如何删除 3 小时前创建的 linux 目录中的文件

python - 读取文件并搜索字符串,如果匹配,则返回 python 中的下一个单词

python - Altair:如何根据最大值在面网格中对线条进行不同的样式设计?

Python 函数 : Optional argument evaluated once?

python - 为什么使用 python 从客户端接收图像后无法从服务器向客户端发送任何内容?