[0, 1, 2, 3],[4, 5, 6, 7, 8],[9, 10, 11],[12, 13, 14, 15],[16, 17, 18, 19, 20],[21, 22, 23]
[0, 1, 2],[3, 4, 5],[6, 7, 8, 9],[10, 11, 12, 13]
[0, 1],[2],[3, 4, 5],[6, 7, 8, 9]
[0, 1, 2, 3],[4, 5, 6, 7],[8],[9, 10, 11, 12],[13, 14, 15]
我有上面的文本文件。问题是该文件中的每个索引都是一个字符串,但是我想将它们转换回整数。 我尝试过:
with open("abc.txt", "r") as text_file:
new_list = [int(line) for line in text_file]
我收到此错误:
ValueError: invalid literal for int() with base 10: '[0, 1, 2, 3],[4, 5, 6, 7, 8],[9, 10, 11],[12, 13, 14, 15],[16, 17, 18, 19, 20],[21, 22, 23]\n'
输出-
[0, 1, 2, 3],[4, 5, 6, 7, 8],[9, 10, 11],[12, 13, 14, 15],[16, 17, 18, 19, 20],[21, 22, 23]
[0, 1, 2],[3, 4, 5],[6, 7, 8, 9],[10, 11, 12, 13]
[0, 1],[2],[3, 4, 5],[6, 7, 8, 9]
[0, 1, 2, 3],[4, 5, 6, 7],[8],[9, 10, 11, 12],[13, 14, 15]
所有这些行都代表包含INTEGERS的列表。
答案 0 :(得分:3)
了解有关ast.literal_eval
的信息尝试一下
import ast
with open("abc.txt", "r") as text_file:
new_list = [list(ast.literal_eval(line)) for line in text_file if line.strip()]
输出:
[[[0, 1, 2, 3], [4, 5, 6, 7, 8], [9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23]],
[[0, 1, 2], [3, 4, 5], [6, 7, 8, 9], [10, 11, 12, 13]],
[[0, 1], [2], [3, 4, 5], [6, 7, 8, 9]],
[[0, 1, 2, 3], [4, 5, 6, 7], [8], [9, 10, 11, 12], [13, 14, 15]]]
答案 1 :(得分:2)
您可以使用literal_eval
和chain
:
from ast import literal_eval
from itertools import chain
with open("abc.txt", "r") as text_file:
new_lines = (list(literal_eval(line)) for line in text_file if line.strip())
new_list = list(chain(*new_lines))
line.strip()
是跳过空行。
答案 2 :(得分:1)
正则表达式是您最好的选择,
for i in range(len(z)):
new_z[i] = int(z[i])
然后剩下的就是将列表中的每个字符串转换为整数,这是一个简单的示例,
remove