python文件读写将txt文件第一行数字赋值给N第二行为以空格分开的数字将其每两个作为二维数组存储到新开数列中
可以使用以下代码实现:
# 读取文件
with open('input.txt', 'r') as file:
lines = file.readlines()
# 获取N和数字列表
N = int(lines[0])
numbers = list(map(int, lines[1].split()))
# 将数字列表每两个作为二维数组存储到新开数列中
array = []
for i in range(0, len(numbers), 2):
array.append([numbers[i], numbers[i+1]])
# 输出结果
print(N)
print(array)
假设input.txt文件内容如下:
3
1 2 3 4 5 6
则运行以上代码后的输出结果为:
3
[[1, 2], [3, 4], [5, 6]]
原文地址: http://www.cveoy.top/t/topic/hOkw 著作权归作者所有。请勿转载和采集!