[英]Separating a tuple and saving it to a file
我目前有以下代码:
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.txt
D://b.txt
和D://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.txt
和c.txt
而不包含任何(
)
[
]
,
>>> 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
尝试这个:
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))
假设元组的数量以及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
我将开始假设获取元组列表的代码有效并且不需要任何调整。
因为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")
您的输出应没有任何类型的括号或括号。
尽管我不确定您在做什么,但是可以以更简单的方式重写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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.