python - Python - 连接多个列表,其中只有一个变量分配给所有列表
问题描述
当一组列表已经分配给一个变量时,如何将多个列表完全连接到一个列表中?
大多数在线建议已经显示了两个或多个变量要连接在一起,但我的只是一个分配给许多列表的变量。我尝试使用嵌套的 For 循环,但导致重复和不连贯的列表。还尝试使用扩展和附加功能,但没有成功。也许我应该用数据框来解决这个问题?
任何帮助深表感谢。如果您有任何问题,请随时提问。
实际代码:
from bs4 import BeautifulSoup as bs
import requests
import re
from time import sleep
from random import randint
def price():
baseURL='https://www.apartmentlist.com/ca/redwood-city'
r=requests.get(baseURL)
soup=bs(r.content,'html.parser')
block=soup.find_all('div',class_='css-1u6cvl9 e1k7pw6k0')
sleep(randint(2,10))
for properties in block:
priceBlock=properties.find_all('div',class_="css-q23zey e131nafx0")
price=[price.text for price in priceBlock]
strPrice=''.join(price) #Change from list to string type
removed=r'[$]' #Select and remove $ characters
removed2=r'Ask' #Select and remove Ask
removed3=r'[,]' #Select and remove comma
modPrice=re.sub(removed,' ',strPrice) #Substitute $ for '_'
modPrice2=re.sub(removed2,' 0',modPrice) #Substitute Ask for _0
modPrice3=re.sub(removed3,'',modPrice2) #Eliminate space within price
segments=modPrice3.split() #Change string with updates into list, remain clustered
for inserts in segments:
newPrice=[inserts] #Returns values from string to list by brackets.
print(newPrice)
price()
实际输出:
#After executing the program
['2157']
['2805']
['0']
['1875']
['2800']
['2265']
['2735']
['3985']
...
...
尝试:
['2157', '2805', '0', '2800',...] # all the while assigned to a single variable.
再次感谢任何帮助。
解决方案
(希望我理解这个问题)
如果每个子列表都是一个变量,您可以执行以下操作之一将它们转换为单个列表:
a = ['2157']
b = ['2805']
c = ['0']
d = ['1875']
e = ['2800']
f = ['2265']
g = ['2735']
h = ['3985']
#Pythonic Way
test = [i[0] for i in [a, b, c, d, e, f, g, h]]
print(test)
#Detailed Way
check = []
for i in a,b,c,d,e,f,g,h:
check.append(i[0])
print(check)
如果您的函数创建列表,那么您只需修改 for 循环以引用您的函数:
#Pythonic Way
test = [i[0] for i in YOUR_FUNCTION()]
print(test)
#Detailed Way
check = []
for i in YOUR_FUNCTION():
check.append(i[0])
print(check)
推荐阅读
- javascript - 节点中的MongoDB聚合函数超时/不返回值
- ansible - 如何检查嵌套字典列表中的项目是否存在于另一个字典列表中?
- google-chrome - 添加 chrome.webRequest 侦听器时出现“没有匹配的签名”错误
- python - 基于另一个数组的一个数组的直方图
- mongoose - 使用 mongoose.findOne 中的文档获取子文档
- javascript - 选择一个时更改单选按钮列表
- flutter - 仿真器错误:x86 仿真当前需要硬件加速,不知道我能做什么
- java - 当实体具有多对多关系时如何使用条件查询?
- python - 是否有任何可行的方法可以一次处理多个 tkinter 条目而无需大量尝试,除了块?
- python-3.x - 无法在二叉树中插入节点