【问题标题】:Converting lists of digits stored as strings into integers Python 2.7将存储为字符串的数字列表转换为整数 Python 2.7
【发布时间】: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


【解决方案1】:

您从文件中获得的所有信息起初都是一个字符串。您必须在程序中解析信息并将其转换为不同的类型和格式。

  • int(distances) 不起作用,因为正如您所观察到的,距离是字符串的列表。您不能将整个列表转换为整数。 (正确答案是什么?)
  • int(distances[0]) 有效,因为您只将第一个字符串转换为整数,而字符串表示整数,因此转换有效。
  • int(distances[1]) 不起作用,因为由于某种原因,列表的第二个和第三个元素之间没有逗号,因此它被隐式连接到字符串 1513 2410。这不能转换为整数,因为它有一个空格。

有几种不同的解决方案可能适合您,但这里有几个明显适合您的用例:

distance.extend([int(elem) for elem in line.split()])

只有当您确定line.split() 返回的列表中的每个元素都可以进行此转换时,这才有效。您也可以稍后一次性完成整个distance 列表:

distance = [int(d) for d in distance]

distance = map(int, distance)

您应该尝试一些解决方案,并实施您认为最适合您工作和可读性的解决方案。

【讨论】:

  • line 顾名思义就是一行;你不应该打电话给.splitlines()。如果每行有一个整数,那么int(line) 应该可以工作。从示例列表来看,该行中可能有多个整数。如果它们是空格分隔的,那么distances.extend(map(int, line.split()))
  • 谢谢您 - 盲目地复制和粘贴,但没有修复。
  • 这是一个非常有启发性的回答,谢谢。我还没有让他们工作,我会尝试 J.F. 的建议,看看是否能解决问题。
  • 感谢您的反馈。我的答案没有提到的一件事是另一个答案中的生成器方法。如果您使用非常大的列表,这可能非常重要,因为虽然列表是在 RAM 中一次构建的(这很慢且很密集),但迭代器和生成器会根据需要一次输出一个元素。对于短名单,这很好。
  • 实施 J.F. 的修复,我们有整数!不错的表演。谢谢你们,先生们。现在我终于可以使用那个矩阵了。
【解决方案2】:

我的猜测是你想分割所有的空格,而不是换行符。如果文件不大,就全部读进去:

distances = map(int, open('file').read().split())

如果某些值不是数字:

distances = (int(word) for word in open('file').read().split() if word.isdigit())

如果文件很大,请使用生成器避免一次全部读取:

import itertools
with open('file') as dists:
  distances = itertools.chain.from_iterable((int(word) for word in line.split()) for line in dists)

【讨论】:

    猜你喜欢
    • 2016-06-04
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2017-07-30
    • 2016-01-01
    • 2015-01-14
    • 2021-06-18
    相关资源
    最近更新 更多