Python -连接多个列表,每个列表只分配一个变量



当一组列表只分配给一个变量时,如何将多个列表连接到一个列表中?

大多数在线建议显示两个或多个变量连接在一起,但我的只是一个变量分配给许多列表。我尝试了一个嵌套的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.

再次感谢您的帮助。

您的代码中的问题是,在段中插入的"循环只接受每个价格,将其放入自己的列表中,然后输出仅包含1个内容的列表。因此,您需要将所有价格添加到同一列表中,然后在循环后输出它。

在你的情况下,你可以使用像这样的列表推导来实现你想要的:

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))
result = []
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
result += [insert for insert in segments]
print(result)
price()

(希望我理解这个问题)

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

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)

如何将多个列表连接到一个列表中,当列表的集合只分配给一个变量时?

在Python中,通常使用列表推导式或itertools.chain来扁平化列表的列表。

from itertools import chain
prices = [
['2157'],
['2805'],
['0'],
['1875'],
['2800'],
['2265'],
['2735'],
['3985'],
]
# list comprehension
[x for row in prices for x in row]
>>> ['2157', '2805', '0', '1875', '2800', '2265', '2735', '3985']
# itertools.chain will return a generator like object
chain.from_iterable(prices)
>>> <itertools.chain at 0x7f01573076a0>
# if you want a list back call list
list(chain.from_iterable(prices))
>>> ['2157', '2805', '0', '1875', '2800', '2265', '2735', '3985']

对于上面的代码,price函数只打印输出而不返回对象。您可以让函数创建一个空列表,并在每次循环遍历属性时向列表中添加内容。然后返回列表。

def price():
# web scrape code
new_price = []
for properties in block:
# processing code

new_price += [x for x in segments]
return chain.from_iterable(new_prices)

最新更新