【问题标题】:Python - Concating numerous lists with only one variable assigned to allPython - 连接多个列表,只有一个变量分配给所有列表
【发布时间】: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


【解决方案1】:

您的代码中的问题是“for inserts in segments”循环仅获取每个价格,将其放入自己的列表中,然后输出仅包含 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()

【讨论】:

  • 非常感谢!我不知道我可以将 += 与列表理解一起使用。
【解决方案2】:

(希望我能理解问题)

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

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)

【讨论】:

  • 您了解问题所在。我的函数的 for 循环是建立数字列表而不是列表的原因。
  • 知道了。我看到公认的解决方案使用相同的策略。始终将列表理解放在口袋里。他们是救生员(字典理解也很强大!)。很高兴它为你解决了:)
【解决方案3】:

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

在 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)

【讨论】:

  • 谢谢,感谢您的帮助!
猜你喜欢
  • 2020-07-02
  • 1970-01-01
  • 2021-03-23
  • 1970-01-01
  • 2022-06-15
  • 1970-01-01
  • 2020-08-14
  • 2019-03-31
  • 1970-01-01
相关资源
最近更新 更多