![](/img/trans.png)
[英]Python - check if 1st element in list of tuples exists in string, if it does add 2nd element from tuple to string
[英]Check that list of tuples has tuple with 1st element as defined string
我正在解析HTML,我只需要獲得像div.content
這樣的選擇器的標簽。
對於解析我正在使用HTMLParser 。 到目前為止,我已經獲得了標簽屬性列表。
它看起來像這樣:
[('class', 'content'), ('title', 'source')]
問題是我不知道如何檢查:
class
元組, 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.