2010-03-10 92 views
0

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

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 

谢谢你的帮助!

回答

1

一种方法是有一个,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() 
+0

他们是在一个字典 - 它被称为*当地人()* :) – 2010-03-10 21:34:04

+1

@伊恩是的,但有些人不喜欢使用它,因为它是一种黑客。 – 2010-03-10 21:50:21

+0

谢谢!如果a,b,c,d,e,f也是数组,那么这样做吗? – lclevy 2010-03-10 21:53:31

2

假设你正在存储所有中间数组的原因。

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 
+1

这不就是重复计算'map(operator.xor,a,b)'吗? – 2010-03-10 21:36:14

+0

@Mark Dickinson,是的。我现在修复它:) – 2010-03-10 22:02:03