假設我有兩個串列:
test_names = [['timothy', 'tim'],["clara"],["jerry", "jer", "j-dog"],]
test_numbers = ['123','234', '345',]
我想將它們保存到一個檔案中,像這樣
123; 蒂莫西; 蒂姆;
234; 克拉拉;
345; 杰瑞 ; 杰爾; j-狗;
然后以某種方式將此檔案回傳到上面的原始串列中?
uj5u.com熱心網友回復:
如果您的意思是保存到 python 檔案,您可以將其匯入,這取決于您所說的保存到檔案的含義
from file import list
print(list)
輸出
mia tim yoyo
但是,如果您的意思是不幸地將其保存到 txt 檔案中
uj5u.com熱心網友回復:
我認為是這樣的:
res = {}
for key in test_keys:
for value in test_values:
res[value] = key
test_values.remove(value)
break
with open("myfile.txt", 'w') as f:
for key, value in res.items():
f.write('%s;%s;\n' % (key, value))
會導致這樣的事情。
123;['蒂莫西','蒂姆'];
234;['克拉拉'];
345;[“杰瑞”,“杰瑞”,“j-狗”];
uj5u.com熱心網友回復:
您的問題似乎包含兩個。最好專注于一個,但別擔心,我會回答兩個
TL; 博士
合并兩個串列
list_A = ['abc', 'def', 'hij']
list_B = ['123','234', '345']
list_AB = []
for i in range(len(list_A)):
list_AB.append([list_A[i], list_B[i]])
# output : [['abc', '123'], ['def', '234'], ['hij', '345']]
保存到檔案
f = open("output.txt", "w")
f.write(str(list_AB))
f.close()
解釋
在 TL;DR 中,我提供了一個簡單的通用解決方案,但我將在此處針對您的具體情況提供更詳細的解決方案
合并兩個串列
我們回圈遍歷串列中的所有元素:
for i in range(len(test_names)):
combined_list = test_names[i]
combined_list.insert(0, test_numbers[i])
list_AB.append(combined_list)
注意 :i將從0(included) 變為len(list_A)(excluded),但如果 的長度與list_B不同 list_A,我們就會遇到問題。如果這種情況是可能的,應該改進這個例子。
保存到檔案
首先打開檔案鏈接
f = open("output.txt", 'w') # 'w' for write (remove old content), we can use 'a' to append at the end of old content
不要忘記在編輯后始終關閉檔案。
f.close() # Else other program can't access the file (appear as being in use by Python)
在此期間,我們會將所有內容寫入檔案。我們將使用一個forloop來遍歷我們里面的所有元素list_AB
for element in list_AB:
f.write(str(element) ' ;\n')
# output :
# ['123', 'timothy', 'tim'] ;
# ['234', 'clara'] ;
# ['345', 'jerry', 'jer', 'j-dog'] ;
這不正是我們想要的。串列顯示為["element1", "element2", ...],但我們想要更漂亮的輸出。我們可以使用.join () :
例如'something'.join(list_AB)
這將連接串列的所有元素,每個元素由一個字串分隔(這里是字串“something”)
for element in list_AB:
f.write(' ; '.join(element) ' ;\n')
# output :
# 123 ; timothy ; tim;
# 234 ; clara;
# 345 ; jerry ; jer ; j-dog;
完美的 :)
(不要忘記關閉你的檔案)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/514434.html
上一篇:標簽無法正確下載
