簡體   English   中英

分隔元組並將其保存到文件

[英]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.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而不包含任何( ) [ ] ,

>>> 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM