我从逗号分隔的文本文件(原始格式alpha_char,空格1,2,3,4,5,6,7,空格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列表或如何将我所拥有的内容转换为字符串列表列表列表的建议。我知道,我在这里非常愚蠢。
答案 0 :(得分:0)
使用列表理解:
>>> 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']]
答案 1 :(得分: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")