【问题标题】:get an array variable in python在python中获取一个数组变量
【发布时间】:2010-03-10 21:15:46
【问题描述】:

我可以通过从要存储的数组名称生成文件名来循环执行此操作吗?

ab = array.array('B', map( operator.xor, a, b ) )
f1 = open('ab', 'wb')
ab.tofile(f1)
f1.close
ac = array.array('B', map( operator.xor, a, c ) )
f1 = open('ac', 'wb')
ac.tofile(f1)
f1.close
ad = array.array('B', map( operator.xor, a, d ) )
f1 = open('ad', 'wb')
ad.tofile(f1)
f1.close
ae = array.array('B', map( operator.xor, a, e ) )
f1 = open('ae', 'wb')
ae.tofile(f1)
f1.close
af = array.array('B', map( operator.xor, a, f ) )
f1 = open('af', 'wb')
af.tofile(f1)
f1.close

感谢您的帮助!

【问题讨论】:

    标签: python arrays variables introspection


    【解决方案1】:

    假设您出于某种原因存储所有中间数组。

    A={}
    for v,x in zip((b,c,d,e,f),'bcdef'):
        fname = 'a'+x
        A[fname] = (array.array('B', map( operator.xor, a, v ) ))
        f1 = open(fname, 'wb')
        A[fname].tofile(f1)
        f1.close
    

    或者类似的东西也应该工作

    A={}
    for x in 'bcdef':
        fname = 'a'+x
        A[fname] = (array.array('B', map(a.__xor__, vars()[x] ) ))
        f1 = open(fname, 'wb')
        A[fname].tofile(f1)
        f1.close
    

    【讨论】:

    • 这不是重复计算map(operator.xor, a, b)吗?
    • @Mark Dickinson,是的。我现在修好了:)
    【解决方案2】:

    一种方法是在字典中包含 a,b,c,d,e,f。然后,您只需执行以下操作:

    for x in 'bcdef':
        t = array.array('B', map( operator.xor, mydict['a'], mydict[x] ) )
        f1 = open(''.join('a',x),'wb')
        t.tofile(f1)
        f1.close()
    

    【讨论】:

    • 它们在一个字典中——它被称为 locals() :)
    • @Ian 是的,但有些人不喜欢使用它,因为它有点像 hack。
    • 我的做法是让 mydict['a'] 返回数组 a。您可以通过将 mydict 替换为 locals() 来使用 locals()。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多