分离元组并将其保存到文件中

时间:2016-02-22 20:06:20

标签: python file tuples

我目前有这段代码:

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.txtb.txtc.txt中,而不是( ) [ ] ,

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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))

答案 2 :(得分: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

答案 3 :(得分: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")

您的输出应该没有任何类型的括号或括号。

答案 4 :(得分: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))