我有一个像这样的numpy数组:
n= [['20015' '20013' '20044' '20001' '20002']
['20002' '20015' '20001' '20013' '20070']
['20044' '20013' '20015' '20001' '20002']
['20071' '20015' '20070' '20001' '20002']]
我希望将此列表打印成以下形式的文件:
20015, 20013, 20044, 20001, 20002
20002, 20015, 20001, 20013, 20070
如何删除列表列表但仍保持组合在一起: 我试过这个:
f=open("myfile.txt, "w")
n=clf.classes_[order[:, -5:]]
print(n)
str1=''.join(str(x) for x in n)
print>>f, str1
f.close()
但这再次将它们列入一个列表。
答案 0 :(得分:2)
如果我理解正确,您只想打印问题中显示的元素。这应该有效:
with open("myfile.txt", "w") as f:
for row in n:
s = ', '.join(str(x) for x in row)
f.write(s)
f.write("\n")
答案 1 :(得分:2)
这应该符合您的要求:
>>> n = [[20015, 20013, 20044, 20001, 20002],
[20002, 20015, 20001, 20013, 20070],
[20044, 20013, 20015, 20001, 20002],
[20071, 20015, 20070, 20001, 20002]]
>>> with open('myfile.txt', 'w') as file:
for row in n:
print(*row, sep=', ', file=file)
>>>
证明它正常工作很简单:
>>> print(open('myfile.txt').read())
20015, 20013, 20044, 20001, 20002
20002, 20015, 20001, 20013, 20070
20044, 20013, 20015, 20001, 20002
20071, 20015, 20070, 20001, 20002
>>>
答案 2 :(得分:1)
试试这个
text = '\n'.join(', '.join(ni) for ni in n)
with open('myfile.txt','w') as f:
f.write(text)