python 问题求解

问题遇到的现象和发生背景

《3.txt》的内容是下面的图片

img

我想要达到的结果

img

with open('3.txt', 'r') as f:
    data = f.readlines()
a=data[0]
b=data[1]

res = [0]*(len(a)+len(b)-1)
for i in range(len(a)):
    for j in range(len(b)):
        res[i+j] += a[i]*b[j]
print(*res)

只有字符串才能写入文件,读出来时也是字符串,所以进行操作时注意转换格式类型


# 打开文件
with open ('s.txt', 'r+') as f:
    # 按行读取,且去除每行末尾的换行符
    lines = [line.strip() for line in f.readlines()]

# # 赋值
a = lines[0]
b = lines[1]

# 把字符串内容转换成数字列表
a_values = a.split(" ")
b_values = b.split(" ")

# 进行你的计算
res = [0]*(len(a_values)+len(b_values)-1)
# print(a_values, b_values)
for i in range(len(a_values)):
    for j in range(len(b_values)):
        res[i+j] += int(a_values[i])*int(b_values[j])

# 将结果转成字符串
res = [str(i) for i in res]
res2 = " ".join(res)
# 查看结果
print(res2)

# 写入文件
with open("3.txt", "w+") as fp:
    fp.write(res2)

img

with open('3.txt', 'r') as f:
    data = f.readlines()
a = data[0].strip()
b = data[1].strip()
print(b)
with open('3.txt', 'w') as f:
    f.write(b)