简体   繁体   English

CSV文件行和列迭代

[英]CSV file row and column iteration

I'm having trouble trying to return row 1 of a csv file, which basically contains a string of data: [0, 300, 30, 521, 53, 462, 642]. 我在尝试返回csv文件的第1行时遇到了麻烦,该文件基本上包含一串数据:[0,300,30,521,53,462,642]。 Basically I'm trying to delete the first column, and then iterate through the first row [300, 30, 521, 53, 462, 642] and append the minimum value (30) into a list called "b". 基本上我正在尝试删除第一列,然后遍历第一行[300,30,521,53,462,642]并将最小值(30)附加到名为“b”的列表中。 Then repeat that with the second row and second column and so on. 然后用第二行和第二列重复它,依此类推。 However, I get an error and I'm not sure what it means. 但是,我收到一个错误,我不确定它的含义。 Can anyone help me with this? 谁能帮我这个? Thank you. 谢谢。

Traceback (most recent call last):
  File "travelsales.py", line 25, in <module>
    nearest(0);
  File "travelsales.py", line 17, in nearest
    for i in reader.next():
StopIteration

Source code: 源代码:

import time
import csv
from itertools import islice

b = list();
reader = csv.reader(open('distance.csv','rU'), delimiter = ' ');
def delete(column):
    for i in reader:
        del i[column];

def nearest(row):
    a = list();
    list(islice(reader, row));
    for i in reader.next():
        a.append(int(i));
    print a;
    b.append(min(a));
    del a[:];
    print b;

delete(0);
nearest(0);

You exhaust your reader in delete - it's similar to reading to the end of a file. 你在删除时耗尽了reader - 这类似于读到文件的末尾。 This approach is overcomplicated. 这种方法过于复杂。 To meet the revised goal of calculating the min of each row, ignoring the nth column in each nth row, I would do this: 为了满足计算每行最小值的修订目标,忽略第n行中的第n列,我会这样做:

b = []
for rownum, line in enumerate(reader):
    b.append(min(int(x) for x in line[:rownum] + line[rownum + 1:])

Since each line list is already created, I think slicing directly is faster than itertools.islice . 由于每个line列表已经创建,我认为直接切片比itertools.islice更快。 List addition vs. itertools.chain I'm not so sure about. 列表添加与itertools.chain我不太确定。

min(min(int(x) for x in line[:rownum]), min(int(x) for x in line[rownum + 1:]))

might also be worth testing. 也许值得测试。

Also, Python doesn't use semicolons. 此外,Python不使用分号。

import csv

def read_csv(fname, **kwargs):
    with open(fname, 'rb') as inf:
        in_csv = csv.reader(inf, **kwargs)
        return list(in_csv)

def nearest(row):
    return min(int(i) for i in islice(row, 1, None))

def main():
    data = read_csv('distance.csv', delimiter=' ')
    b = [nearest(row) for row in data]

if __name__=="__main__":
    main()

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

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