【问题标题】:Convert list of lists of string to list of lists of int将字符串列表列表转换为 int 列表列表
【发布时间】:2013-10-13 11:52:28
【问题描述】:

我已从逗号分隔的文本文件(原始格式 alpha_char,space 1,2,3,4,5,6,7, space alpha_characters newline char)中读取数据并输出[['1,2,3,4,5,6,7'],['7,5,3,9,8,2,4'], etc](即一个字符串)并希望将它们转换为[[1,2,3,4,5,6,7],[7,5,3,9,8,2,4], etc](即int列表)。因此,我将不胜感激有关如何将文本文件中的数据读入 int 列表列表或如何将我拥有的字符串列表列表转换为 int 列表列表的建议。我知道我在这里很愚蠢。

【问题讨论】:

  • 如果它真的是一个逗号分隔的文件,你能跳过手动的东西和import csv并使用它吗?

标签: python python-3.x string list


【解决方案1】:

使用列表推导:

>>> with open('file.txt') as f:
...     rows = [line.strip().split(',') for line in f]
...
>>> rows
[['1', '2', '3', '4', '5', '6', '7'], ['7', '5', '3', '9', '8', '2', '4']]
>>> nums = [list(map(int, row)) for row in rows]
>>> nums
[[1, 2, 3, 4, 5, 6, 7], [7, 5, 3, 9, 8, 2, 4]]

你也可以使用csv module:

>>> import csv
>>>
>>> with open('file.txt') as f:
...     reader = csv.reader(f)
...     rows = [row for row in reader]
...
>>> rows
[['1', '2', '3', '4', '5', '6', '7'], ['7', '5', '3', '9', '8', '2', '4']]

【讨论】:

  • 谢谢。我试图按照您的描述做很多事情,但是在错误的地方。我现在得到 int base10 的无效文字,所以我需要再看看我做了什么。很好的答案
【解决方案2】:

要过滤数字并转换输出,您可以执行以下操作:

new_list = [ [ int(x) for x in convert_list.split(",") if x.isdigit() ] for sublist in oldlist for convert_list in sublist ]

如果你想知道你输入的不是数字,你可以省略.isdigit()并使用try except:

try:
    [ [ int(x) for x in convert_list.split(",") ] for sublist in oldlist for convert_list in sublist ]
except ValueError:
    print("bad input")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    相关资源
    最近更新 更多