我正在尝试将for循环的输出及其对应的变量保存在文本文件中。但是,当我执行以下操作时,我只会得到最后一行作为输出。
a = [1,2,3,4]
b = [4,5,6,7]
c = [5]
file=open("my_output.txt", 'a')
for i, j in zip(a, b):
z = (i**2)*j+c[0]
print (z)
z = str(z)
file.write(z + "\n")
file.close()
我的输出:
117
我正在寻找的东西:
a,b,c,z
1,4,5,9
2,5,5,25
3,6,5,59
4,7,5,117
感谢您的支持。预先谢谢你。
答案 0 :(得分:0)
用于计算z的代码。然后将a,b,c,z写入文件。
a = [1, 2, 3, 4]
b = [4, 5, 6, 7]
c = [5]
zs = []
col = ['a','b','c','z']
file = open("my_output.txt", 'a')
for i, j in zip(a, b):
z = (i ** 2) * j + c[0]
print(z)
zs.append([i,j,c[0],z])
file.write(str(zs))
file.close()
答案 1 :(得分:0)
您的代码中的问题是您在循环之外进行编写,因此仅获得了最后一个值。在循环内编写将解决此问题。
有一种更简单的方法。 // dependencies
const AWS = require('aws-sdk');
var JSZip = require('jszip');
// get reference to S3 client
const s3 = new AWS.S3();
exports.handler = async (event, context, callback) => {
// Read options from the event parameter.
const srcBucket = event.Records[0].s3.bucket.name;
// Object key may have spaces or unicode non-ASCII characters.
const srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " "));
// Download the file from the S3 source bucket.
try {
const params = {
Bucket: srcBucket,
Key: srcKey
};
const data = await s3.getObject(params).promise();
var zip = JSZip.loadAsync(data.Body);
return zip.then(function(result){
var entries = Object.keys(result.files).map((name) =>{
if(name.indexOf("TestStatus") != -1){
return result.files[name];
}
}).filter(notUndefined => notUndefined !== undefined);
var listOfPromises = entries.map((entry) => {
return entry.async("text")
.then((u8) => {
return [entry.name, u8];
}).catch(error => console.error(error));
});
var promiseOfList = Promise.all(listOfPromises);
promiseOfList.then(function (list) {
console.log(list.toString());
});
});
} catch (error) {
context.fail(error);
return;
}
};
可以写入文件:
print