如何从元组列表中删除项目

时间:2019-01-11 12:25:40

标签: python

我正在收集位于Wikipedia信息框中的信息。我将数据存储在列表中。但是,我检索的第一个span标签存储图像。我想从列表中删除图像。

    for my_tables in my_table:
    row1 = my_table.find_all('th',{'scope':'row'})

    row2 = my_table.find_all('td')

    for my_tables in my_table.find_all('td'):

    grab_text2 = (my_tables.text, my_tables.next_sibling)

    row2_list.append(grab_text2)

    print (row2_list)

当前输出为:

[('', None), 
('11 August 1902\xa0(1902-08-11)Paris, France', None), 
('29 July 1991(1991-07-29) (aged\xa088)Paris, France', None), 
('\xa0France', None), ('\xa0French Army', None), ('1921-1959', None), 
('General de brigade', None), 
('Mobile Group 2Mobile Group 1Operational Group North-West', None), 
('World War IIFirst Indochina War*Battle of Dien Bien Phu', None)] 

'('',None)'是图像。

1 个答案:

答案 0 :(得分:2)

如果您要删除任何空白项目,只需简单的列表理解即可

row2_new = [item for item in row2_list if item[0]]

row2_new现在将包含

[('11 August 1902\xa0(1902-08-11)Paris, France', None), ('29 July 1991(1991-07-29) (aged\xa088)Paris, France', None), ('\xa0France', None), ('\xa0French Army', None), ('1921-1959', None), ('General de brigade', None), ('Mobile Group 2Mobile Group 1Operational Group North-West', None), ('World War IIFirst Indochina War*Battle of Dien Bien Phu', None)]

如果只想删除第一个元素,那么将执行简单的切片操作。

row2_new = row2_list[1:]