简体   繁体   English

从CSV到列表的字符串-Python

[英]String from CSV to list - Python

I don't get it. 我不明白 I have a CSV data with the following content: 我有一个包含以下内容的CSV数据:

wurst;ball;hoden;sack
1;2;3;4
4;3;2;1

I want to iterate over the CSV data and put the heads in one list and the content in another list. 我想遍历CSV数据,并将标题放在一个列表中,将内容放在另一个列表中。 Heres my code so far: 到目前为止,这是我的代码:

data = [ i.strip() for i in open('test.csv', 'r').readlines() ]

for i_c, i in enumerate(data):
    if i_c == 0:
            heads = i
    else:
            content = i

heads.split(";")
content.split(";")
print heads

That always returns the following string, not a valid list. 总是返回以下字符串,而不是有效列表。

wurst;ball;hoden;sack

Why does split not work on this string? 为什么split在此字符串上不起作用?

Greetings and merry Christmas, Jan 一月的问候和圣诞快乐

The split method returns the list, it does not modify the object in place. split方法返回列表,它不会在适当位置修改对象。 Try: 尝试:

heads = heads.split(";")
content = content.split(";")

I've noticed also that your data seems to all be integers. 我还注意到,您的数据似乎都是整数。 You might consider instead the following for content : 您可以考虑以下content

content = [int(i) for i in content.split(";")]

The reason is that split returns a list of strings, and it seems like you might need to deal with them as numbers in your code later on. 原因是split返回一个字符串列表,似乎您以后可能需要将它们作为数字处理。 Of course, disregard if you are expecting non-numeric data to show up at some point. 当然,如果您期望非数字数据会在某个时候出现,请忽略。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM