合并循环获得的列表

2024-04-19 09:28:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近才开始使用python,但遇到了一个问题。你知道吗

# function that tells how to read the urls and how to process the data the
# way I need it.


def htmlreader(i):
    # makes variable websites because it is used in a loop.
    pricedata = urllib2.urlopen(
        "http://website.com/" + (",".join(priceids.split(",")[i:i + 200]))).read()

    # here my information processing begins but that is fine.
    pricewebstring = pricedata.split("},{")
    # results in [[1234,2345,3456],[3456,4567,5678]] for example.
    array1 = [re.findall(r"\d+", a) for a in pricewebstring]

    # writes obtained array to my text file
    itemtxt2.write(str(array1) + '\n')

i = 0
while i <= totalitemnumber:
    htmlreader(i)
    i = i + 200

也可以查看脚本中的注释。你知道吗

这是一个循环,每次都会给我一个数组(由array1定义)。你知道吗

因为我把它打印到一个txt文件中,它会产生一个带有单独数组的txt文件。 我需要一个大数组,所以它需要合并htmlreader(I)的结果。你知道吗

所以我的输出是这样的:

[[1234,2345,3456],[3456,4567,5678]]
[[6789,4567,2345],[3565,1234,2345]]

但我想:

[[1234,2345,3456],[3456,4567,5678],[6789,4567,2345],[3565,1234,2345]]

有什么办法吗?你知道吗


Tags: thetoinreadthatismyit
1条回答
网友
1楼 · 发布于 2024-04-19 09:28:22

因为您希望将所有元素收集到一个列表中,所以可以简单地将它们收集到另一个列表中,方法是将其展平如下

def htmlreader(i, result):
    ...
    result.extend([re.findall(r"\d+", a) for a in pricewebstring])

i, result = 0, []
while i <= totalitemnumber:
    htmlreader(i, result)
    i = i + 200

itemtxt2.write(str(result) + '\n')

在这种情况下,由re.findall(列表)创建的结果被添加到result列表中。最后,将整个列表作为一个整体写入文件。你知道吗

如果上面显示的方法令人困惑,那么就这样更改它

def htmlreader(i):
    ...
    return [re.findall(r"\d+", a) for a in pricewebstring]

i, result = 0, []
while i <= totalitemnumber:
    result.extend(htmlreader(i))
    i = i + 200

相关问题 更多 >