首页 > 解决方案 > 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.

再次感谢任何帮助。

标签: pythonpython-3.xlistdataframe

解决方案


(希望我理解这个问题)

如果每个子列表都是一个变量,您可以执行以下操作之一将它们转换为单个列表:

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)

推荐阅读