1

我是 Python 的新手,正在寻找我想做的例子。我不确定这个循环有什么问题,我想做的是逐行读取一个 csv 文件,并为每一行:

  • 用逗号分隔
  • 删除第一个条目(这是一个名称)并将其存储为name
  • 将所有其他条目转换为浮点数
  • 在我的班级中存储name和浮动条目Community

这就是我目前正在尝试的:

class Community:
    num = 0
    def __init__(self, inName, inVertices):
        self.name = inName
        self.vertices = inVertices
        Community.num += 1

allCommunities = []
f = open("communityAreas.csv")
for i, line in enumerate(f):
    entries = line.split(',')
    name = entries.pop(0)
    for j, vertex in entries: entries[j] = float(vertex)

    print name+", "+entries[0]+", "+str(type(entries[0]))

    allCommunities.append(Community(name, entries))
f.close()

我得到的错误是:

>>>>> PYTHON ERROR!!! Traceback (most recent call last):
  File "alexChicago.py", line 86, in <module>
    for j, vertex in entries: entries[j] = float(vertex)
ValueError: too many values to unpack

值得指出的是,这是在 omegalib 中运行的,这是一个用于在 C 中运行并解释 Python 的视觉集群的库。

4

3 回答 3

2

我认为您忘记了enumerate()第 86 行的功能;应该

for j, vertex in enumerate(entries): entries[j] = float(vertex)
于 2013-09-17T03:30:02.433 回答
1

I may not be absolutely certain about what you want to achieve here, but converting all the element in entries to float, should not this be sufficient?: Line 86:

entries=map(float, entries)
于 2013-09-17T04:22:36.277 回答
1

如果总是有一个名称,然后是可变数量的浮点值,那么听起来您需要拆分两次:第一次的 maxsplit 为 1,另一次则尽可能多次。例子:

name, float_values = line.split(',',1)
float_values = [float(x) for x in float_values.split(',')]
于 2013-09-17T03:30:22.420 回答