如何在python中只获得一个列表?

时间:2016-08-09 17:55:09

标签: python list

我对某些列表几乎没有帮助,所以我有这部分代码:

get_attributeName = \
    soup.find(True, {"class": ["product-attributes", "product-attribute-value"]}).find_all('li')

allDataList = []        
for attData, attValues in get_attributeName:
    data = [attData, attValues.text]            
    allDataList.append(data)
    print(allDataList)

print(allDataList)结果后的结果为:

[['Year: ', '2013']]
[['Year: ', '2013'], ['Color: ', 'Yellow']]
[['Year: ', '2013'], ['Color: ', 'Yellow'], ['Package: ', '5kg']]
[['Year: ', '2013'], ['Color: ', 'Yellow'], ['Package: ', '5kg'], ['Comment: ', 'Null']]
[['Year: ', '2013'], ['Color: ', 'Yellow'], ['Package: ', '5kg'], ['Comment: ', 'Null'], ['Product: ', 'mushrooms']]
[['Year: ', '2013'], ['Color: ', 'Yellow'], ['Package: ', '5kg'], ['Comment: ', 'Null'], ['Product: ', 'mushrooms'], ['Forest: ', 'NULL']]
[['Year: ', '2013'], ['Color: ', 'Yellow'], ['Package: ', '5kg'], ['Comment: ', 'Null'], ['Product: ', 'mushrooms'], ['Forest: ', 'NULL'], ['Country: ', 'France']]

我需要结果只有最后一行,所有列表都在一个列表中,如下所示:

[['Year: ', '2013'], ['Color: ', 'Yellow'], ['Package: ', '5kg'], ['Comment: ', 'Null'], ['Product: ', 'mushrooms'], ['Forest: ', 'NULL'], ['Country: ', 'France']]

1 个答案:

答案 0 :(得分:2)

您的代码在构建时每次迭代打印列表。只是不打印每次迭代;在 for循环完成后(如果有的话),只打印

get_attributeName = soup.find(True,{"class": ["product-attributes", "product-attribute-value"]}).find_all('li')

allDataList = []        
for attData, attValues in get_attributeName:
    data = [attData, attValues.text]            
    allDataList.append(data)
print(allDataList)