【发布时间】:2014-05-05 12:57:38
【问题描述】:
除其他外,我的项目需要从文件中检索距离信息,将数据转换为整数,然后将它们添加到 128 x 128 矩阵中。
我在读取线路数据时陷入僵局。
我用以下方式检索它:
distances = []
with open(filename, 'r') as f:
for line in f:
if line[0].isdigit():
distances.extend(line.splitlines())`
这会产生一个字符串列表。
同时
int(distances) #does not work
int(distances[0]) # produces the correct integer when called through console
不过,空格foobar的程序稍后再说。 列表示例:
['966']['966', '1513' 2410'] # the distance list increases with each additional city. The first item is actually the distance of the second city from the first. The second item is the distance of the third city from the first two.
int(distances[0]) #returns 966 in console. A happy integer for the matrix. However:
int(distances[1]) # returns:
Traceback(最近一次调用最后一次): 文件“”,第 1 行,在 ValueError: int() 以 10 为底的无效文字:'1513 2410'
我稍微偏爱更多的 Python 解决方案,例如列表理解等,但实际上 - 非常感谢任何和所有帮助。
感谢您的宝贵时间。
【问题讨论】:
-
您似乎在
'1513'之后添加了另一个引用,而ValueError输出中没有。 -
感谢您采用这种方法,这让我对如何处理我的矩阵有了一个好主意。将距离加载到其中后,它应该能够给出任意两个给定城市的距离。看起来不错。
标签: string list python-2.7 matrix integer