2010-03-10 48 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