2

I have a numpy array like this:

 n=   [['20015' '20013' '20044' '20001' '20002']
     ['20002' '20015' '20001' '20013' '20070']
     ['20044' '20013' '20015' '20001' '20002']
     ['20071' '20015' '20070' '20001' '20002']]

I wish to print this list into a file in the form of :

20015, 20013, 20044, 20001, 20002
 20002, 20015, 20001, 20013, 20070

How can I get rid of the list of list but still keep the grouped 5 together: I tried this out:

    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()

But this again puts them in a list.

0

3 Answers 3

2

If I'm understanding correctly, you just want to print the elements as shown in your question. This should work:

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")
Sign up to request clarification or add additional context in comments.

Comments

2

This should do what you asked for:

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

>>> 

Proving that it works properly is simple:

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

>>> 

Comments

1

Try this

text = '\n'.join(', '.join(ni) for ni in n)
with open('myfile.txt','w') as f:
    f.write(text)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.