如何连接所有列表(每个列表都是我的for循环)

2024-10-02 22:27:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我在用python beautifulsou,requests,Pandas library爬行网页, 试图通过for循环收集多个页面中多个项目的信息。 但当我运行这些代码时, 我只能将列表彼此分开,所以我想编辑此代码,使其由一个列表串联起来。你知道吗

  • 嗯,实际上我的问题不是“串联列表”本身。 我已经知道了,但问题是, 如果函数给出了一个“列表”的结果, 如何编辑代码以生成一个结果,该结果将“一个列表”连接在一起,或者返回[[list]、[list]、[list]]表单,以便轻松连接在一起。你知道吗

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]]

Tags: 代码列表forgettitlepagecontentfind
1条回答
网友
1楼 · 发布于 2024-10-02 22:27:03

使用+操作符连接任意数量的列表

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]

这些都是简单的例子,然后你试图实现,但一个类似的方法将解决你的问题在最后!你知道吗

相关问题 更多 >