简体   繁体   English

如何获取我的列表以打印出每一行?

[英]How do I get my list to print out every line?

I'm a little confused as to why this is not working. 我有点困惑为什么这不起作用。 I'm trying to get my program to read every line out a csv file change it from a string to a float and then print it out line by line. 我正在尝试让我的程序读取csv文件的每一行,将其从字符串更改为浮点数,然后逐行打印出来。

csv_list = open('example_data.csv','rb')
lists= csv_list.readlines()
csv_list.close()


for lines in lists:
    lists_1 = lists.strip().split()
    list_2 = [float(x) for x in lists_1]
print list_2

Any help would be appreciated. 任何帮助,将不胜感激。

First, don't use readlines . 首先,不要使用readlines Simply iterate over file 只需遍历文件

for lines in csv_list:
   ...

second, use csv library for reading http://docs.python.org/2/library/csv.html 其次,使用csv库阅读http://docs.python.org/2/library/csv.html

In your exapmple, it is csv, so don't split by whitespace but comma or semicolon. 例如,它是csv,所以不要用空格分开,而要用逗号或分号分隔。

Try this: 尝试这个:

import pprint

with open('example_data.csv','rb') as csv_list:
    lists= csv_list.readlines()
    lists_1 = []
    lists_2 = []
    for lines in lists:
        lists_1.append(lines.strip().split())
        list_2.append([float(x) for x in lists_1])
    pprint.pprint(list_2)
for lines in lists:
    lists_1 = lines.strip().split()   # 'lines' here
    list_2 = [float(x) for x in lists_1]
    print list_2 # print your list in a loop

print list_2需要与循环的其余部分缩进同一级别,并且应该为lines.strip().split()

print list_2 is outside of the for loop. print list_2在for循环之外。 You need to indent it. 您需要缩进。

Judging by the file name, I assume that the fields in your file is separated by comma. 从文件名来看,我假设文件中的字段用逗号分隔。 If that is the case, you need to split the line using the comma: 在这种情况下,您需要使用逗号来分隔行:

    lists_1 = lists.strip().split(',')

Better yet, use the csv module. 更好的是,使用csv模块。 Here is an example: 这是一个例子:

import csv 

with open('example_data.csv', 'rb') as f:
    csvreader = csv.reader(f)
    for line in csvreader:
        line = [float(x) for x in line] # line is now a list of floats
        print line

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

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