繁体   English   中英

检查元组列表是否具有元组的元组作为定义的字符串

[英]Check that list of tuples has tuple with 1st element as defined string

我正在解析HTML,我只需要获得像div.content这样的选择器的标签。

对于解析我正在使用HTMLParser 到目前为止,我已经获得了标签属性列表。

它看起来像这样:

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

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

  1. List有第一个元素名为class元组,
  2. 元组第1个元素(它将是第2个元素)的值是content ;

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

循环遍历元素时:

if ('class', 'content') in element_attributes:
    #do stuff
l = [('class', 'content'), ('title', 'source')]

('class', 'content') in l

返回True,因为至少有一个元组,其中'class'为first,'content'为second元素。

你现在可以使用它:

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

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

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

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

要检查其中一个元组元素是否具有某个值,您可以使用过滤器函数:

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

第一个问题)

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

第2个问题)

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

注意:根据我的理解,第二个问题意味着如果第二个元组值中的一个是“内容”,则需要为true。

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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