【问题标题】:Check that list of tuples has tuple with 1st element as defined string检查元组列表是否具有第一个元素作为定义字符串的元组
【发布时间】:2012-03-14 13:37:29
【问题描述】:

我正在解析 HTML,我只需要获取带有 div.content 之类的选择器的标签。

我使用HTMLParser进行解析。到目前为止,我得到了标签的属性列表。

看起来像这样:

[('class', 'content'), ('title', 'source')]

问题是我不知道如何检查:

  1. 列表有元组,第一个元素称为class
  2. 元组第一个元素(它将是第二个元素)的值是content

我知道这是一个简单的问题,但我对 Python 也很陌生。感谢您的任何建议!

【问题讨论】:

    标签: python list parsing tuples


    【解决方案1】:

    循环遍历元素时:

    if ('class', 'content') in element_attributes:
        #do stuff
    

    【讨论】:

    • 如果你想让这个条件匹配第二个元素的通配符呢?
    • 如果你不知道元组中的第二个元素怎么办?我想要类似的东西:list_of_tuples 中的 if ('key','anyvalue') 。有没有办法做到这一点?
    【解决方案2】:
    l = [('class', 'content'), ('title', 'source')]
    
    ('class', 'content') in l
    

    返回 True,因为至少有一个 'class' 作为第一个元素,'content' 作为第二个元素的元组。

    您现在可以使用它了:

    if ('class', 'content') in l:
        # do something
    

    【讨论】:

      【解决方案3】:

      值得注意的是,HTML 的“类”属性可以是一个空格分隔的 CSS 类列表。例如,您可以使用<span class='green big'>...</span>。听起来您真正想知道的是给定的 HTML 元素是否具有特定的 CSS 类(给定 (attribute,value) 对的列表)。在这种情况下,我会使用这样的东西:

      element_attributes =  [('class', 'content'), ('title', 'source')]
      is_content = any((attr=='class') and ('content' in val.split())
                       for (attr, val) in element_attributes)
      

      当然,如果你确定你关心的所有元素都只有一个 CSS 类,那么 sr2222 的答案会更好/更简单。

      【讨论】:

        【解决方案4】:

        要检查元组元素之一是否具有某些值,您可以使用过滤功能:

        tuples_list = [('class', 'content'), ('title', 'source')]
        if filter(lambda a: a[0] == 'class', tuples_list):
            # your code goes here
        if filter(lambda a: a[1] == 'content', tuples_list):
            # your code goes here
        

        过滤器会为您提供所有符合您条件的元组:

        values = filter(lambda a: a[1] == 'content', tuples_list)
        # values == [('class', 'content')]
        

        如果你确定它们在同一个元组中:

        if ('class', 'content') in tuples_list:
            # your code goes here
        

        【讨论】:

          【解决方案5】:

          第一个问题)

          if len(list) > 1:
              if list[0][0] == 'class':
                  return True`
          

          第二个问题)

          for elem in list:
              if elem[1] == 'content':
                  return True
          

          注意:据我了解,第二个问题的意思是,如果第二个元组值中的一个是“内容”,那么你想要 true。

          【讨论】:

            【解决方案6】:

            试试这个:

            l = [('class', 'content'), ('title', 'source')]
            check = False
            for item in l:
              if item[0] == 'class':
                check=True
                print item[1]
            print "List have tuple with 1st element called class: %s" check
            

            【讨论】:

              猜你喜欢
              • 2016-06-04
              • 1970-01-01
              • 1970-01-01
              • 2021-12-07
              • 2015-08-09
              • 1970-01-01
              • 1970-01-01
              • 2019-03-09
              • 1970-01-01
              相关资源
              最近更新 更多