Python 合并循环获得的列表

Python 合并循环获得的列表,python,list,loops,Python,List,Loops,我最近才开始使用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://webs

我最近才开始使用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
但我想:

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

你知道我该怎么做吗?

既然你想在一个列表中收集所有元素,你可以简单地将它们收集到另一个列表中,方法如下

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

您可以使用
+
组合数组。您也可以使用
[html\u reader(i)for i in range(0,totalitemnumber,200)]
是,但每次数组都是由array1定义的。所以我不能添加它们,对吗?与第一次array1=[[123423456],[345645675678]]一样,这是因为它将array1写入txt文件而存储的。然后在第二次运行时,由于新的web地址,array1被重新定义。您需要通过一个返回调用传递
array1
,然后将它们追加或添加到主数组中,或者使用我上面提到的列表理解。如果你的目标是拥有一个数组,那么一旦你将对象写入文本文件,你就不能对它们进行操作——你也可能想要对它进行pickle(我猜这是为了进一步的python处理使用,因为你需要一个数组)。是的,他没有正确地使用
findall
。另外,他的数据可能太大,无法作为一个完整的列表来编写,但在这种情况下,它是一个python数组是没有意义的,因为您无论如何都无法将其加载到内存中。@user3467349是的,我认为他最好像我在回答中所示的那样在列表中收集数据。谢谢,效果非常好。我需要一些时间来理解它,但会设法:)接受和+1@SecondLemon谢谢:)请检查列表中的
append
extend
方法之间的差异。
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