Append lists for CSV output in Python

时光总嘲笑我的痴心妄想 提交于 2019-12-13 06:02:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!