【发布时间】:2021-02-09 14:32:02
【问题描述】:
当一组列表已经分配给一个变量时,如何将多个列表完全连接到一个列表中?
大多数在线建议都显示了两个或多个变量要连接在一起,但我的只是一个分配给多个列表的变量。我尝试使用嵌套的 For-Loop,但导致重复和不连贯的列表。还尝试使用扩展和附加功能,但没有成功。也许我应该用数据框来解决这个问题?
非常感谢任何帮助。如果您有任何问题,请随时提出。
实际代码:
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.
再次感谢任何帮助。
【问题讨论】:
-
请发表您的意见。
标签: python python-3.x list dataframe