Python:速记的“as”关键字

时间:2013-07-02 01:56:42

标签: python iteration shorthand

简单的问题:在Python中迭代时是否可以分配速记引用,就像这样(这不起作用):

class SomeClass:
    class_dict = {0:0,1:1,2:2,3:3}

newClass = SomeClass()

for n in newClass.class_dict as thedict: # assigning a shorthand reference "thedict" to newClass.class_dict
    print(thedict[n])

2 个答案:

答案 0 :(得分:3)

我认为你想要这个(使用n, o将键/值对重复为iteritems()):

class SomeClass:
    class_dict = {0:0,1:1,2:2,3:3}

newClass = SomeClass()

for n, o in newClass.class_dict.iteritems():
    print(o)

答案 1 :(得分:1)

此外,如果您想追求最初的想法,您可以简单地将class_dict分配给新名称。对这两个字典所做的任何更改都会影响它们,因为它们在别名中是真正的内存字典。

例如

class SomeClass:
class_dict = {0:0,1:1,2:2,3:3}

newClass = SomeClass()

thedict = newClass.class_dict

for n in thedict:
    thedict[n] = thedict[n] + 1
    print(thedict[n])

print(newClass.class_dict)

将输出

1
2
3
4
{0: 1, 1: 2, 2: 3, 3: 4}