首页 \ 问答 \ 从for循环中更新外部变量值的最佳方法?(best way to update values of outer-scope variables from within a for-loop?)

从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
更新时间:2023-11-28 18:11

最满意答案

由于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 the fetch() 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);

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)