python - 如何连接所有列表(每个列表都是我的 for 循环)
问题描述
我正在通过 python BeautifulSoup、requests、Pandas 库抓取网页,试图通过 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]]
解决方案
使用+
运算符连接任意数量的列表
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]
这些是比您要实现的更简单的示例,但是类似的方法将最终解决您遇到的问题!
推荐阅读
- javascript - 每 48 小时在三个 classList 之间切换
- kubernetes - 如何在我们的网络中的 kubernetes 上托管一个简单的 html 代码?
- mysql - 在 SQL 中查找比赛的获胜者
- syntax - SAS PROC GENMOD - 为什么一致的语法会为两个不同的二进制变量产生不同的参考类别?
- prolog - 当没有更多结果要显示时,为什么 SWI-Prolog 不显示“假”
- reactjs - React:从状态数组元素中获取内容
- html - 使用 flexbox,菜单栏将主体的其余部分推离中心
- python - 有没有办法让这个更容易?
- python - 有没有办法在不实际添加函数的情况下向抽象基类添加动态函数“提示”?
- php - 常规如何匹配彼此靠近的两个单词,中间有共享字母