Python单变量多列表合并问题:如何将单个变量关联的多个列表合并为一个列表
Hey there! I see exactly what's going on here—your current code is creating a tiny single-element list every time in the loop and printing it immediately, which is why you're getting all those separate ['xxx'] outputs. Let's fix this by collecting all those values into one big list, plus I'll cover the DataFrame option you asked about too.
Step 1: Fix the List Collection Issue
The core problem is you're not accumulating values into a single list. Instead of creating a new newPrice list each iteration, initialize an empty list at the start of your function, then add each price value to it as you process them.
Here's the revised code with comments explaining the changes:
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)) # Initialize an empty list to collect ALL price values final_price_list = [] for properties in block: priceBlock=properties.find_all('div',class_="css-q23zey e131nafx0") price=[price.text for price in priceBlock] strPrice=''.join(price) removed=r'[$]' removed2=r'Ask' removed3=r'[,]' modPrice=re.sub(removed,' ',strPrice) modPrice2=re.sub(removed2,' 0',modPrice) modPrice3=re.sub(removed3,'',modPrice2) segments=modPrice3.split() # Instead of making a new list each time, add each value to our final list for inserts in segments: final_price_list.append(inserts) # Append the string directly # Now print the single merged list print(final_price_list) price()
This will give you your desired output:
['2157', '2805', '0', '1875', '2800', '2265', '2735', '3985', ...]
Step 2: Using a DataFrame (If You Need It)
Absolutely, you can use a Pandas DataFrame to work with this data—great for further analysis, filtering, or exporting. First, make sure you have Pandas installed (pip install pandas), then modify the end of the function like this:
import pandas as pd # ... (keep all the previous code up to collecting final_price_list) # Convert the list to a DataFrame price_df = pd.DataFrame(final_price_list, columns=['Apartment Price']) print(price_df)
This will give you a neat table with one column of all your prices, which is perfect if you want to do things like convert values to integers, filter out the '0' entries (from "Ask" prices), or calculate averages.
Why Your Previous Attempts Didn't Work
- Nested loops/duplicates: If you tried nesting loops incorrectly, you might have been adding the same values multiple times or not structuring the accumulation right.
- extend vs append:
extend()adds elements from an iterable (like another list), whileappend()adds a single element. Sinceinsertsis a string (not a list), usingappend()is the right call here—if you triedextend(inserts), it would split the string into individual characters, which is why that messed up your list structure.
内容的提问来源于stack exchange,提问作者Bellycose

