2016-02-22 73 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)) 
相关问题