【问题标题】:How is this code converted into python 2?这段代码是如何转换成 python 2 的?
【发布时间】:2015-06-25 23:36:48
【问题描述】:
import csv

with open('scores.csv') as handle:
    reader = csv.reader(handle)
    for row in list(reader)[1:]:
        user, *scores = row
        average = sum([int(score) for score in scores]) / len(scores)
        print (
            "{user} has average of {average}".format(user=user,average=average)
        ) 

由于 *scores,此代码在 python 2.7 中不起作用。我不知道如何将其更改为 python 2.7?

此代码取自此线程:Row Average CSV Python

【问题讨论】:

  • 您还需要调整average 行。在 Python 3 中,/ 是“真正的除法”,但在 Python 2 中不是——结果将被截断为整数。最简单的方法是先将其中一个值转换为 float
  • 请注意,使用list(reader)[1:] 效率非常低,因为它将文件中的所有内容都拉到一个列表中。在单独的行上使用next(reader, None),然后使用for row in reader:;这将从 CSV 中读取一行并将其丢弃,从而有效地跳过该行。见Skip the headers when editing a csv file using Python

标签: python python-2.7 csv


【解决方案1】:

换行

user, *scores = row

user, scores = row[0], row[1:]

注意除了上面的,你还应该改变

average = sum([int(score) for score in scores]) / len(scores)

average = sum([int(score) for score in scores]) / float(len(scores))

因为 Python 2.X 中的除法是整数除法。或者,您也可以从未来导入真实的部门

from __future__ import division

如果要使用整数除法,请使用双正斜杠 '//'

【讨论】:

    【解决方案2】:

    您应该使我们的代码尽可能与 python 3 兼容,并在未来导入:

    from __future__ import division, print_function
    import csv
    
    with open('scores.csv') as handle:
        reader = csv.reader(handle)
        next(reader) # header
        for row in reader:
            user = row[0]
            scores = row[1:]
            average = sum(int(score) for score in scores) / len(scores)
            print (
            "{user} has average of {average}".format(user=user, average=average)
            ) 
    

    【讨论】:

      猜你喜欢
      • 2022-11-16
      • 1970-01-01
      • 2021-09-05
      • 2018-12-12
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多