[英]Taking each column as its own list
With a csv the goal is to create a list for each column in the csv, ignoring the first row, which is the header row. 使用csv的目标是为csv中的每一列创建一个列表,而忽略第一行,即标题行。
var_a var_b
a 1
b 2
c 3
listA = [var_a] = ['a','b','c']
listB = [var_b] = [1,2,3]
Right now, my only solution is to create an empty list and iterate over the csv position by position and append it to these empty lists. 现在,我唯一的解决方案是创建一个空列表,然后逐个位置遍历csv位置并将其附加到这些空列表中。
If you have memory enough, you can get a bit more elegance: 如果您有足够的内存,则可以得到更多的优雅:
with open('the.csv') as f:
next(f)
list_of_rows = list(csv.reader(f))
listA = [row[0] for row in list_of_rows]
listB = [int(row[1]) for row in list_of_rows]
but it's not enormously different from what you say you're doing now -- just a tad more elegant. 但这与您现在说的话并没有太大不同-只是更优雅一点。
(In your example the second columns somehow gives a list of int
s while the first one gives a list of str
s -- there's no black magic to do that , either, so I explicitly used int
where it appears needed). (在你的榜样,第二列莫名其妙给人的列表int
s,而第一个给出的列表str
秒-没有黑魔法要做到这一点 ,无论是的,所以我明确地使用int
地方出现需要)。
Have you checked out the csv tools that ship with python? 您是否签出了python随附的csv工具? These can help shrink your code down. 这些可以帮助您缩减代码。
Also, in terms of the complexity, iterating over each element is the best you can do. 同样,就复杂性而言,最好对每个元素进行迭代。 If it's easier, you can try loading everything into a matrix 如果更简单,您可以尝试将所有内容加载到矩阵中
both = [[a, 1], [b, 2], [c, 3]]
(which is what python's csv tools will naturally do for you), and the transposing (这是python的csv工具自然会为您完成的工作),以及转置
z = list (zip (*both))
listA = list (z[0]) # zip gives a tuple, make a list so you can edit
listB = list (z[1])
You can use dict reader and create a list by header: 您可以使用字典阅读器并按标题创建列表:
import csv
result={}
with open(fn) as f:
for line in csv.DictReader(f, delimiter='\t'):
for k in line:
result.setdefault(k, []).append(line[k].strip())
print result
Prints: 打印:
{'var_a': ['a', 'b', 'c'], 'var_b': ['1', '2', '3']}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.