开发者

Basic Python question: referencing original variable inside for loop?

Quick, newbie Python scoping question. How can I make sur开发者_JAVA技巧e that the original variables get changed in the for-loop below?

for name in [name_level_1, name_level_2, name_level_3, name_level_4]:
     name = util.translate("iw", "en", name.encode('utf-8'))
print name_level_1

In other words, I want the print statement to print out the changed variable, not the original. Python doesn't have pointers, right?

Thanks!


I don't think you can do what you want to do.

To do something similar you can use indexing into the array:

names = [name_level_1, name_level_2, name_level_3, name_level_4]
for i in range(len(names)):
     names[i] = util.translate("iw", "en", names[i].encode('utf-8'))
print names[0]

But normally for this sort of thing you would just use a list comprehension:

names = [name_level_1, name_level_2, name_level_3, name_level_4]
names = [util.translate("iw", "en", name.encode('utf-8')) for name in names]


Python has references and objects instead of pointers (from a conceptual level).

What you want to do is assign the new value of name_level_1 to some name that exists after the loop.

So, either unwrap the loop and use each name where you need it, e.g.

name_level_1_translated = util.translate("iw", "en", name_level_1.encode('utf-8'))
print name_level_1_translated

name_level_2_translated = util.translate("iw", "en", name_level_2.encode('utf-8'))
do_stuff(name_level_2_translated)

or, if you're going to use each name the same way, just create a list and use that everywhere.

names = [name_level_1, name_level_2, name_level_3, name_level_4]
translated_names = [util.translate("iw", "en", name.encode('utf-8')) for name in names]
for name in translated_names:
    print name

You can also access them by index:

print names[0]


make name_level_1 an object:

class LevelOne(object):
   def __init__(self):
       self.x = 3

name_level_1 = LevelOne()
count = 0
for name in [name_level_1, LevelOne(), LevelOne()]:
    name.x = count

print name_level_1.x


You can manipulate the names in the global namespace using globals():

for name,value in globals().items():
    if name.startswith("name_level_"):
        globals()[name] = util.translate("iw", "en", value.encode('utf-8'))

However, storing the names in an array or dict is probably a better idea.


Avoid polluting your namespace with lots of related variables, group them together in a dictionary or a list. e.g.

NAMES = { 'level_1': 'something', 'level_2': 'something else',
    'level_3': 'whatever', 'level_4': 'and so on' }
for name in NAMES:
     NAMES[name] = util.translate("iw", "en", NAMES[name].encode('utf-8'))
print NAMES['level_1']
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜