2016-02-22 71 views
0

我現在有這樣的代碼:分離一個元組並將其保存到一個文件

from collections import OrderedDict 
a = [(1), (7), (3), (1)] 
b = [(2), (4), (7), (4)] 
c = [(8), (1), (3), (3)] 
d = (list(OrderedDict((sub[0], sub) for sub in sorted(zip(a, b, c))).values())) 
print(d) 

輸出:

[(1, 4, 3), (3, 7, 3), (7, 4, 1)] 

目前我想保存到3個文件。 D://a.txtD://b.txtD://c.txt

D://a.txt我要救:

1 
3 
7 

D://b.txt我要救:

4 
7 
4 

而在D://c.txt我想保存:

3 
3 
1 

我知道如何保存:

with open("D:\\a.txt", "a") as myfile1: 
    myfile1.write(num1) 
    myfile1.write("\n") 

或者與b.txt:

with open("D:\\b.txt", "a") as myfile2: 
    myfile2.write(num2) 
    myfile2.write("\n") 

在這種情況下NUM1和NUM2使用,如:

for num1 in a: 
    myfile1.write(num1) 
    myfile1.write("\n") 

我的目標是將號碼存入a.txt,b.txtc.txt而不是任何()[],

+0

請描述其輸出的數字應選擇更詳細的,因爲我沒有得到有關任何暗示的標準。 – albert

+0

@albert它只是索引0去索引1去b和索引2去c – SirParselot

回答

1
>>> d 
[(1, 4, 3), (3, 7, 3), (7, 4, 1)] 
>>> with open('a.txt','w') as fa, open('b.txt','w') as fb, open('c.txt','w') as fc: 
...  for a,b,c in d: 
...   fa.write(str(a) + '\n') 
...   fb.write(str(b) + '\n') 
...   fc.write(str(c) + '\n') 
...   
>>> !cat a.txt 
1 
3 
7 
0

試試這個:

letters = ("a", "b", "c") 
for i, nums in enumerate(zip(d)): 
    with open("D:\\{}.txt".format(letters[i]), "a") as myfile: 
     myfile.write("\n".join(str(num) for num in nums)) 
0

假設組的數目,以及條目在d每個元組的數量可以改變:

for i, nums in enumerate(zip(*d)): 
    fname = '/tmp/%s.txt' % chr(ord('a') + i) 
    with open(fname, 'w') as f: 
     f.write('\n'.join('%s' % n for n in nums)) 

這樣你得到你想要的:

!cat /tmp/a.txt 
1 
3 
7 
!cat /tmp/b.txt 
4 
7 
4 
!cat /tmp/c.txt 
3 
3 
1 
0

我將開始假設獲取元組列表的代碼工作並且不需要任何調整。

由於d是元組列表,我將分配3個變量,每個元組分配一個變量以使事情變得更簡單。

a = d[0] #(1,4,3) 
b = d[1] #(3,7,3) 
c = d[2] #(7,4,1) 

現在,是時候循環它們,並將值分配給文件。

for x in a: 
    with open("D:\\a.txt", "a") as file: 
     file.write(x) 
     file.write("\n") 

for y in b: 
    with open("D:\\b.txt", "a") as file: 
     file.write(y) 
     file.write("\n") 

for z in c: 
    with open("D:\\c.txt", "a") as file: 
     file.write(z) 
     file.write("\n") 

你的輸出應該是自由的任何類型的支架或括號的。

0

雖然我不確定自己在做什麼,但是您可以用更簡單的方式重寫d的定義,然後可以創建e以配對每個結果元組中的條目。

a = [(1), (7), (3), (1)] 
b = [(2), (4), (7), (4)] 
c = [(8), (1), (3), (3)] 
d = sorted(zip(a, b, c))[1:] # [(1, 4, 3), (3, 7, 3), (7, 4, 1)] 
e = list(zip(*d)) # [(1, 3, 7), (4, 7, 4), (3, 3, 1)] 

然後,你可以寫在每個文件爲:

for name, values in zip(['a', 'b', 'c'], e): 
    with open('D:\\{}.txt'.format(name), 'w') as myfile: 
     myfile.write('\n'.join(map(str,values)) 
相關問題