从for循环中更新外部变量值的最佳方法?(best way to update values of outer-scope variables from within a for-loop?)
这个问题与我之前的问题有关: python更新外部传递的值来自for循环 。
来自Perl背景,通过引用传递变量并从子范围内更新值从来没有问题,如下面的for循环示例中所示:
#!/usr/bin/perl my ($str1,$str2) = ('before','before'); print "before - str1:'$str1', str2:'$str2'\n"; foreach my $str($str1,$str2){$str = 'after'} print "after - str1:'$str1', str2:'$str2'\n";
我在Python中理解这是不可能的,因为变量是按值而不是按引用导入的 ,我在Python中找到的唯一解决方案到目前为止实现了我所需要的是:
def changeValue(str): return 'after' str1 = 'before' str2 = 'before' for s in str1,str2: print s str1 = changeValue(str1) str2 = changeValue(str2) for s in str1,str2: print s
虽然不理想,如果我可以在for-loop中进行函数'changeValue'调用,而不是像上面那样单独调用它们,那就没关系了 - 但是我回到了原来的“无法通过引用传递变量”问题。
我确信必须有一种简单且不那么复杂的Pythonic方法来实现我追求的目标吗?
This question is related to my earlier question here: python update outer passed value from within a for loop.
Coming from a Perl background it has never been a problem to pass a variable by reference and update the value from within a child scope as in the for-loop example below:
#!/usr/bin/perl my ($str1,$str2) = ('before','before'); print "before - str1:'$str1', str2:'$str2'\n"; foreach my $str($str1,$str2){$str = 'after'} print "after - str1:'$str1', str2:'$str2'\n";
I understand in Python this is not possible as variables are imported by-value rather than by-reference, the only solution I've found within Python so far which achieves exactly what I need is:
def changeValue(str): return 'after' str1 = 'before' str2 = 'before' for s in str1,str2: print s str1 = changeValue(str1) str2 = changeValue(str2) for s in str1,str2: print s
Although not ideal this would be OK if I could make the function 'changeValue' calls from within a for-loop - rather than calling them individually as above - but then I am back to the original "can't pass a variable by reference" problem.
I am sure that there must be a simple and less convoluted Pythonic way to achieve what I'm after?
原文:https://stackoverflow.com/questions/12303018
最满意答案
由于CSV只是文本,因此解决方案是使用
fetch()
API的response.text()
方法。https://developer.mozilla.org/en-US/docs/Web/API/Body/text
文本一旦载入,就像从文件中解析CSV一样简单。 如果您希望将对象作为输出,则必须将标题包含在CSV中(您的是)。
我已经包含下面的代码片段。 它不会在SO上运行,因为SO会将AJAX请求的原点设置为null。 所以我还包括一个链接到一个有效的codepen解决方案。
fetch('https://docs.google.com/spreadsheets/d/e/KEY&single=true&output=csv') .then(response => response.text()) .then(transform); function transform(str) { let data = str.split('\n').map(i=>i.split(',')); let headers = data.shift(); let output = data.map(d=>{obj = {};headers.map((h,i)=>obj[headers[i]] = d[i]);return obj;}); console.log(output); }
钢笔
https://codepen.io/randycasburn/pen/xjzzvW?editors=0012
编辑
我应该补充说,如果你真的想要这个JSON字符串(根据你的问题),你可以运行
json = JSON.stringify(output);
Since CSV is simply text, the solution is the use the
response.text()
method of thefetch()
API.https://developer.mozilla.org/en-US/docs/Web/API/Body/text
Once the text is onboard, it is as simple as parsing the CSV out of the file. If you want objects as an output it is imperative the headers are included in the CSV (which yours are).
I've included the code snippet below. It won't run on SO because SO sets the origin to null on AJAX requests. So I've also included a link to a working codepen solution.
fetch('https://docs.google.com/spreadsheets/d/e/KEY&single=true&output=csv') .then(response => response.text()) .then(transform); function transform(str) { let data = str.split('\n').map(i=>i.split(',')); let headers = data.shift(); let output = data.map(d=>{obj = {};headers.map((h,i)=>obj[headers[i]] = d[i]);return obj;}); console.log(output); }
Pen
https://codepen.io/randycasburn/pen/xjzzvW?editors=0012
Edit
I should add that if you truly want this in a JSON string (per your question), you can run
json = JSON.stringify(output);
相关问答
更多-
流不可读(Stream was not readable)[2022-02-26]
您无法从流中读取两次。 通话结束后: responseStream.CopyTo(output); ...您已经阅读了流中的所有数据。 没有什么可以阅读,你不能“回放”流(例如寻找到开头),因为它是一个网络流。 不可否认,我希望它只是空洞而不是抛出错误,但细节并不重要,因为尝试这样做并不是一件有用的事情。 如果要制作相同数据的两个副本,最好的选择是将其复制到磁盘上,然后读取刚写入的文件。 (或者,您可以通过复制到MemoryStream将其读入内存,然后您可以重复该流并重复读取它。但是如果您已经将它保存到 ... -
为什么我的Stream不可读?(Why is my Stream not Readable?)[2023-01-30]
File.OpenWrite创建一个不可读的流。 如果您要读取和写入流,则需要使用File.Open(localPath, FileMode.Open, FileAccess.ReadWrite) 。 此外,您可以使用FileMode.OpenOrCreate ,这将消除您的File.Exists条件的需要。 File.OpenWrite creates a non-readable stream. If you're going to be reading and writing to the strea ... -
在'data'事件处理函数中修改局部变量不会改变响应中发送的数据。 而不是管道,在'data'事件处理函数中写入数据,并在'end'事件处理函数中结束响应。 只是修改了一下 html.on('data', function(data) { // <-- here I try to use the template text data = data.toString().replace('{title}', title); console.log(data); res.write(data); } ...
-
是的,它可能与FileReader和csv : import csv from 'csv'; // ... const onDrop = onDrop = (e) => { const reader = new FileReader(); reader.onload = () => { csv.parse(reader.result, (err, data) => { console.log(data); }); }; ...
-
如何在服务器端拆分JSON,然后在客户端加入并流式传输(How to split JSON in server side then join and stream it in client side)[2022-02-14]
创建文件块的一种方法是使用fread() PHP函数。 使用fread我们可以指定我们想要从文件中读取的字节数。 所以你可以做的是在从数据库创建文件后/创建文件块时创建。 这是你如何创建块。 $fp = fopen("jsonfile.txt",'r'); $i=1; while(!feof($fp)) { $json_contents = fread($fp,4000); file_put_contents('json_chunk_'.$i.'.txt',$json_contents); ... -
如果要在客户端创建JSON(也称为字符串化),可以使用json.org中的字符串化器。 关于它在这里使用的更多细节。 然后,您将使用正常的jQuery.ajax(...)如下所示: function sendJSON(dataToStringify) { var stringifiedData = JSON.stringify(dataToStringify); jQuery.ajax({ url: 'http://some.url.here', data: {stri ...
-
由于CSV只是文本,因此解决方案是使用fetch() API的response.text()方法。 https://developer.mozilla.org/en-US/docs/Web/API/Body/text 文本一旦载入,就像从文件中解析CSV一样简单。 如果您希望将对象作为输出,则必须将标题包含在CSV中(您的是)。 我已经包含下面的代码片段。 它不会在SO上运行,因为SO会将AJAX请求的原点设置为null。 所以我还包括一个链接到一个有效的codepen解决方案。 fetch('https: ...
-
羽毛在客户端的错误(Feathers errors on a client side)[2022-06-16]
花几分钟修复它,它只是实现.toJSON()方法... Spend some minutes fixing it, it's simply implement .toJSON() method... -
如何在客户端(JS或JQuery)将JSON转换为XML [重复](How to convert JSON to XML in Client side(JS or JQuery) [duplicate])[2023-09-26]
尝试使用JQuery http://api.jquery.com/jQuery.parseXML/ 您可以创建一个空的xml文档,如: $.parseXML("")然后在从中获取的文档上设置属性。 举例说明: var doc = $.parseXML(" ") var json = {key1: 1, key2: 2} var xml = doc.getElementsByTagName("xml")[0] var key, elem for (key in json) { ... -
有内置的过滤器: {{ obj | json }} {{ obj | json }} 有关json filter的更多信息: https : //docs.angularjs.org/api/ng/filter/json There is builtin filter for this: {{ obj | json }} More info about json filter: https://docs.angularjs.org/api/ng/filter/json