问题
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.
回答1:
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).
回答2:
Make a list of strings instead of dealing with them as separate variables, then you can loop over them with enumerate:
strs = ['before', 'before']
for i, s in enumerate(strs):
print s
strs[i] = "after"
print strs
回答3:
strs = ['before', 'before']
strs[:] = ['after' for s in strs]
回答4:
str1 = 'before'
str2 = 'before'
import sys
currentobject = sys.modules[__name__]
for i in 'str1', 'str2':
setattr(currentobject, i, 'after')
for i in str1,str2:
print "%s" % (i)
来源:https://stackoverflow.com/questions/12286231/python-update-outer-passed-value-from-within-a-for-loop