[英]Objects in column of csv file are lists. How do I combine these into one giant list using Python?
I have a csv file whose columns consists entirely of lists like ['spam', 'eggs', ..., 'spam']. 我有一个csv文件,其列完全由[[spam],'eggs',...,'spam']等列表组成。 Ideally I want to aggregate all of these lists together into one giant list, but am running into trouble doing that;
理想情况下,我想将所有这些列表汇总到一个巨大的列表中,但是这样做很麻烦。 initially I thought something like:
最初我以为是这样的:
import csv
with open(<filepath>, 'r') as csvfile:
reader = csv.reader(csvfile)
lst = []
for row in reader:
lst += row
So my idea was basically that each "row in reader" would more-or-less be the list ['spam', 'eggs', ..., 'spam'] and that I could just combine these together one at a time, but that evidently ran into some problems. 所以我的想法基本上是,每个“读者行”或多或少都是列表['spam','eggs',...,'spam'],我可以一次将它们组合在一起,但显然会遇到一些问题。 Is there anyway to make this work?
反正有做这项工作吗? Any help is appreciated!
任何帮助表示赞赏!
Edit: To give more context, let's say this csv has one column only and three rows, each of which is literally "['spam', 'eggs', 'spam', 'eggs']". 编辑:为了提供更多的上下文,我们假设此csv只有一列和三行,每行实际上是“ ['spam','eggs','spam','eggs']”。 The desired output would be:
所需的输出将是:
"['spam', 'eggs', 'spam', 'eggs', 'spam', 'eggs', 'spam', 'eggs', 'spam', 'eggs', 'spam', 'eggs']"
But the output I'm getting from my code instead is: 但是我从代码中得到的输出是:
"[['spam', 'eggs', 'spam', 'eggs'], ['spam', 'eggs', 'spam', 'eggs'], ['spam', 'eggs', 'spam', 'eggs']]
So the question is around how to fix this kind of issue. 因此,问题在于如何解决此类问题。
A file containing ['spam', 'eggs', 'spam', 'eggs']
is not a CSV file. 包含
['spam', 'eggs', 'spam', 'eggs']
的文件不是CSV文件。 The content appears more like a string literal version of a Python list. 内容看起来更像是Python列表的字符串文字版本。 Given that you might be better off treating them as Python list literals, and parsing them with
ast.literal_eval()
: 鉴于您最好将它们视为Python列表文字,并使用
ast.literal_eval()
解析:
from ast import literal_eval
with open(<filepath>) as infile:
lst = []
for line in infile:
lst.extend(literal_eval(line))
If your input file contains this: 如果您的输入文件包含以下内容:
['spam', 'eggs', 'spam', 'eggs'] ['more', 'spam', 'more', 'eggs'] ['spam', 'spam', 'spam', 'spam']
lst
would end up containing this: lst
最终将包含此:
['spam', 'eggs', 'spam', 'eggs', 'more', 'spam', 'more', 'eggs', 'spam', 'spam', 'spam', 'spam']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.