python更新for循环中的外部传递值 [英] python update outer passed value from within a for loop

查看:165
本文介绍了python更新for循环中的外部传递值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是如何通过一个变量的引用? - 但我仍然找不到一个简单的解决方案,以下所示的问题:我怎么能改变的外部字符串变量的值在一个for-loop

  str1 ='之前'
str2 ='之前'

str1,str2:
print%s%(i)
i =after

for str1,str2:
print%s% (i)

感谢以下有帮助的回复,但是他们并没有真正帮助我解决具体的问题,下面的代码是不太通用的,但更好地反映了我的用例:

pre $ import $ feed $ $ $ bd = ://feeds.feedburner.com/FrontlineAudiocastPbs?format = xml')
name = d.feed.title [:127]
description = d.feed.subtitle [:255]

strs = [name,desc (strs):
try:
strs [i] = unicode(strs [i])
除外:
strs [我] =无效的Unicode检测!

为名字,描述:
print s

你可以看到两个原始的字符串变量没有被更新。 for循环的目的是检测和处理格式错误的字符串,如赋值给'description'..所以任何'相关'的建议将不胜感激。

我喜欢 下面的列表理解切片分配方法,并理想地使用该技术。就是用不同的方式来构造你的数据,例如使用:

$ p $ {code> d = {'str1':'before','str2' :'之前'}
为我在d:
打印d [i]
d [i] =之后

重要的是这个变量是可变的(正如在你的链接中讨论的那样)

My question is a slight variation of How do I pass a variable by reference? - however I still can't find a simple solution to the problem illustrated below: how can I alter the values of the outer string variables from within a for-loop?

str1 = 'before'
str2 = 'before'

for i in str1,str2:
    print "%s" % (i)
    i = "after"

for i in str1,str2:
    print "%s" % (i)

Thanks for the helpful responses below however they haven't really helped with my specific problem, the code below is less generic but better reflects my use case:

import feedparser
d = feedparser.parse('http://feeds.feedburner.com/FrontlineAudiocastPbs?format=xml')
name = d.feed.title[:127]
description = d.feed.subtitle[:255]

strs = [name,description]
for i, s in enumerate(strs):
    try:
      strs[i] = unicode(strs[i])
    except:
      strs[i] = "Invalid unicode detected!"

for s in name,description:
  print s 

You can see that the two original string variables are not being updated. The for-loop is intended to detect and handle malformed string such as the assignment to 'description'.. so any 'associated' advice would be appreciated.

I like the elegance of the list comprehension slice assignment approach below and would ideally use that technique.

解决方案

One workaround is to structure your data differently, for example by using:

d = {'str1': 'before', 'str2': 'before'}
for i in d:
    print d[i]
    d[i] = "after"

The important thing is that this variable is mutable (as discussed in your link).

这篇关于python更新for循环中的外部传递值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆