这个python代码如何读取csv文件?

时间:2012-02-02 15:54:41

标签: python loops iterator

任何人都可以向我详细解释这段代码的详细内容:

i = int(0)
L = list();
for row in reader:
    if i != 0: 
        tempNum = convertStr(row[3].replace(",", ""))
        L.append(tempNum)

    i += 1
f.close()

tempTotal = 0.0
for value in L:
    tempTotal += value
avgStrideDist = tempTotal / i

3 个答案:

答案 0 :(得分:2)

这段代码风格很糟糕。您应该阅读并理解python教程。也就是说,我已经用一种希望让它更容易理解的方式重写了它。

reader = ??? # seriously, where is it defined?
f = ??? # likewise, where?

# don't call it L ferchrissakes
next(reader) # ignore first element for whatever reason - this assumes reader is some kind of generator object
converted_strs = [convertStr(row[3].replace(",", "")) for row in reader] #what's convertStr??
f.close() # close the file object held in f, whatever it is.

total = sum(L)
avgStrideDist = float(total)/ len(converted_strs)

如果你对这些数据做的唯一事情是计算均值,你可能会使用reduce之类的东西来生成表达式而不是列表推导,以避免必须遍历数据两次;或许你不会,因为这种方法很容易理解。

答案 1 :(得分:0)

i = int(0)    # make an int and initialize it to 0. Equivalent to i=0
L = list();    # make a new empty list. Equivalent to L=[]. Semicolon is unnecessary but not wrong
for row in reader:    # I'm guessing there's a variable called reader initialized somewhere before
    if i != 0: # if the variable i contains any value other than 0
        tempNum = convertStr(row[3].replace(",", "")) # call an external function called convertStr (defined somewhere else) on the input parameter of the fourth item in a list called row (indexing starts at 0, so item at index 3 is the 4th item). Make sure that this item does not contain commas before giving it to convertStr. Assign the result to a variable called tempNum
        L.append(tempNum) # add the value of tempNum to the end of L

    i += 1 # increment i
f.close() # close the file that you were reading (I assume this was opened before)

# get the average of all the values in the list L
tempTotal = 0.0
for value in L:
    tempTotal += value
avgStrideDist = tempTotal / i

基本上,所有这些都相当于:

total = sum(map(int, (i.replace(',', '') for i in reader)))
avgStrideDist = total/float(len(reader))

希望这有帮助

答案 2 :(得分:0)

首先,这还不足以提供我们需要的所有细节,但假设这里的读者是这样的:

 f = open(filename)   
 reader = csv.reader(f, dialect='excel')

您可以在此处查看有关csv.reader

的更多详细信息

现在有了这段代码:

 i = int(0)
 L = list();
 for row in reader:
    if i != 0: 
        tempNum = convertStr(row[3].replace(",", ""))
        L.append(tempNum)
    i += 1

除了第一行之外的所有行,分割行并用''替换第4个元素中的','字符并将其添加到列表中。这是python的丑陋编码,你可以像下面这样重写:

 L = [row[3].replace(',', "") for row in lines[1:]]

 L = list()
 for idx, row in enumerate(reader):
     if idx:
          L.append(row[3].replace(',', '')

其余的只是结果列表中的平均值。这也可以通过简单地执行以更优雅的方式完成:

 avg = sum(L) / len(L)