1

我已经从逗号分隔的文本文件中读取数据(原始格式 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 列表列表的建议。我在这里很愚蠢,我知道。

4

2 回答 2

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模块

>>> 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']]
于 2013-10-13T11:58:46.267 回答
0

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

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

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

try:
    [ [ int(x) for x in convert_list.split(",") ] for sublist in oldlist for convert_list in sublist ]
except ValueError:
    print("bad input")
于 2013-10-13T12:21:17.657 回答