按行拆分数组

Split array by rows

我有一个非常基本的 problem.I 已经写了一段代码,它打开一个包含数字 1 2 3 4 5 6 7 8 9 的 .txt 文件。然后它对所有内容进行平方并写入其他文件。 现在我想添加到这个代码程序中,它将所有这些数字分成几行并重写,就像这样:

1 4 9
16 25 36
49 64 81

我的代码已经:

n=[]
dane = open("num.txt", "r")

for i in dane:
  i = i.replace('\n','')
  for j in i.split(' '):
        j = int(j)
        j = j**2
        n.append(j)

nowy = open("newnum.txt","w")
nowy.write(str(n))
nowy.close()

您编写的代码在编写部分工作正常。为此,您需要将最后三行代码更改为

nowy = open("newnum.txt","w")
for i in range(0,len(n),3):
    nowy.write("{} {} {}\n".format(n[i],n[i+1],n[i+2]))
nowy.close()

for 循环可以解释为,

  • 通过使用 range 函数的第三个参数(称为 step)一次生成 3 个列表 n 循环。
  • 一次将三个值写入文件,以换行符终止

更改代码行后的输出符合预期

1 4 9
16 25 36
49 64 81

参考:

你可以试试这个:

strNew = ''
dane = open("num.txt", "r")
row = 0
for i in dane:
  i = i.replace('\n','')
  for j in i.split(' '):
    row += 1
    j = int(j)
    j = j**2
    if (row % 3) == 0:
        strNew += str(j)+'\n'
    else:
        strNew += str(j) + ' ' # it can be ' ' or '\t'

nowy = open("newnum.txt","w")
nowy.write(strNew)
nowy.close()

结果是:

1 4 9
16 25 36
49 64 81
n=[]
dane = open("num.txt", "r")

for i in dane:
  i = i.replace('\n','')
  for j in i.split(' '):
        j = int(j)
        j = j**2
        # new code added
        # why str(j)? Because array in Python can only have one type of element such as string, int, etc. as opposed to tuple that can have multiple type in itself. I appended string because I wanna append \n at the end of each step(in outer loop I mean)
        n.append(str(j))

  # new code added
  n.append("\n")

nowy = open("newnum.txt","w")
nowy.write(str(n))
nowy.close()

作为对@Bhargav 回答的补充,according to the doc [a] 将数据系列聚类为 n 长度组的可能惯用语 [是] 使用 zip(*[iter(s)]*n)"。 =30=]

您也可以使用 star 将 list/tuple 解压为 format 函数调用的参数。

所有这些都将导致写作部分更加 Pythonic(或者更确切地说是 crypto-Pythonic?)版本:

with open("newnum.txt","w") as nowy:
    for sublist in zip(*[iter(n)]*3):
        nowy.write("{} {} {}\n".format(*sublist))

请注意使用上下文管理器(with 语句)以确保在所有情况下退出块时 正确关闭文件。由于其他更改将受到讨论,因此稍后是 必须 -- 你应该明确地养成使用它的习惯
(顺便说一句,您是否注意到您从未关闭过 dane 文件?使用上下文管理器管理该资源可以避免一个简单的错误...)