问题
At the moment I am scraping data from the web and want to output it into CSV. Everything is working fine but as soon as I append more than one list in the iteration the list has the wrong format.
I start with sth like this:
list = [a, b, c]
list_two = [d, e, f]
list_three = [g, h, i]
first iteration:
list = [list, list_two]
# list = [[a, b, c], [d, e, f]]
second iteration:
list = [list, list_three]
I get:
# list = [[[a, b, c], [d, e, f]], [g, h, i]]
I want to have:
# list = [[a, b, c], [d, e, f], [g, h, i]]
Please help me! I guess it is a easy thing but I do not get it. And I actually struggle to find information on how to append lists.
回答1:
Just use + to concatenate two lists :
list = [ list, list_two ]
list += [ list_three ]
You could also use append :
list = [ list ]
list.append( list_two )
list.append( list_three )
回答2:
You can create a helper list and use append:
For example
helperList = []
list = ['a', 'b', 'c']
list_two = ['d', 'e', 'f']
list_three = ['g', 'h', 'i']
helperList.append(list)
helperList.append(list_two)
helperList.append(list3_three)
#helperList >>> [['a', 'b', 'c'], ['d', 'e', 'g'], ['g', 'h', 'i']]
来源:https://stackoverflow.com/questions/16748940/append-lists-for-csv-output-in-python