首页 > 解决方案 > 如何连接所有列表(每个列表都是我的 for 循环)

问题描述

我正在通过 python BeautifulSoup、requests、Pandas 库抓取网页,试图通过 for 循环收集许多页面中许多项目的信息。但是当我运行这些代码时,我只能得到彼此分开的列表,所以我想编辑这段代码以连接一个列表。

Windows、Jupyter 笔记本、Python

def a(content):
    ptag_title=content.find("p",{"class":"title"})
    ptag_price=content.find("p",{"class":"price-sale"})
    return {"title":ptag_title.text, "price":ptag_price.text}

def get_pd_page(url):
    result = requests.get(url)
    bs_obj = bs4.BeautifulSoup(result.content,"html.parser")
    pbl=bs_obj.find("div",{"class":"product-box-list"})
    contents = pbl.findAll("div",{"class":"content"})
    pdinfo_list = [get_pdinfo(content ) for content in contents]
    return pdinfo_listn = 10

urls = [None] * n
fix_str = "https://www.abcdef.com"

for page_num in range(0,n):
    page_str = fix_str + str(page_num+1)
    urls[page_num] = page_str
    page_products = get_pd_page(urls[page_num])
    print(page_products)

每个页面的结果都是单独的列表。

[{'title':a, 'price'=b},{'title':c, 'price'=d}] [{'title':d, 'price'=e},{'title':f, 'price'=g]

我想列一个完整的清单。

[{'title':a, 'price'=b},{'title':c, 'price'=d},{'title':d, 'price'=e},{'title':f, 'price'=g]

或者,至少,通过列表列表

[[{'title':a, 'price'=b},{'title':c, 'price'=d}],[{'title':d, 'price'=e},{'title':f, 'price'=g]]

标签: python

解决方案


使用+运算符连接任意数量的列表

In [19]: li1 = [1,2,3]                                                                                                         

In [20]: li2 = [4,5,6]                                                                                                         

In [21]: li1+li2                                                                                                               
Out[21]: [1, 2, 3, 4, 5, 6]

或者使用列表推导来连接列表列表中的子列表,也称为flattening列表

In [23]: li = [[1,2,3],[4,5,6],[7,8,9]]  

In [30]: flat_list = [item for sublist in li for item in sublist]                                                              

In [31]: flat_list                                                                                                             
Out[31]: [1, 2, 3, 4, 5, 6, 7, 8, 9]

这些是比您要实现的更简单的示例,但是类似的方法将最终解决您遇到的问题!


推荐阅读