【问题标题】:How is this python code reading the csv file? [closed]这个 python 代码是如何读取 csv 文件的? [关闭]
【发布时间】:2012-02-02 15:54:41
【问题描述】:

谁能详细解释一下这段代码的含义:

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

【问题讨论】:

  • 你在哪里找到了这段代码?我们不能告诉你它在做什么,因为没有定义 reader。您是从 python excel 阅读器之类的工具中找到的吗?
  • (a) 哪一部分让您感到困惑? (b) 你没有包括所有变量的定义。特别是,reader 未在此代码中定义。
  • 我认为缺少一些东西。我看到f.close(),但我没有看到任何打开文件的东西。而且,reader 对象是在哪里创建的?
  • 另外,这段代码的风格很糟糕。
  • @CraigHarrison:您可以并且应该编辑您的问题。

标签: python loops iterator


【解决方案1】:

这段代码的风格很糟糕。您应该阅读并理解 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,虽然您已经删除了原始代码中细微的一对一错误,但您的代码并不是相当等效的。
  • @Wooble:我明确地忽略了reader 中的第一个元素。是你说的那个错误吗?或者还有其他的 (row != len(L)?)?
  • 是的,原始代码会在平均值中使用的计数加 1,即使它跳过了该行。授予,您的版本可能是他们打算要做的......
【解决方案2】:
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))

希望对你有帮助

【讨论】:

  • 谢谢,这很有帮助。如果我有超过 14 个声望点,我会投票给你。我是新人。
  • 没有汗水!很高兴我能帮上忙。但是你真的需要更好地表达你的问题。关注其他人在您的问题上留下的 cmets ;-)
【解决方案3】:

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

 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)

【讨论】:

    猜你喜欢
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多