-1

I need to store the print value of this code into a variable so that I can dump it into a text file.

for i, j, v in sorted(zip(m.row, m.col, m.data)):
            if doc_id == -1:
                print(str(j) + ':' + "{:.4f}".format(v), end=' ')
            else:
                if doc_id != i:
                    print()
                print(str(j) + ':' + "{:.4f}".format(v), end=' ')
            doc_id = i

I used list comprehension and appending it into a variable but didn't help.

Saurabh
  • 95
  • 1
  • 1
  • 8
  • If you're unfamiliar with storing values in variables, you should look up a tutorial like the [official Python tutorial](https://docs.python.org/3.5/tutorial/index.html). – TigerhawkT3 Nov 27 '16 at 23:41
  • Additionally, the code in this question is from an answer to [a previous question of yours](http://stackoverflow.com/questions/40742105/converting-a-text-corpus-to-a-text-document-with-vocabulary-id-and-respective-tf). This site is not a coding service; please do some of your own work. – TigerhawkT3 Nov 27 '16 at 23:52

1 Answers1

0

When you do print, you ask the Python to pass the content to the stdin i.e print the content to the console. If you want to store it in variable, you need to remove the content from print() and store in variable. For example in your case as:

my_list = []
my_var = str(j) + ':' + "{:.4f}".format(v)
my_list.append(my_var)  # add variable to list

# Uncomment this if you also want to print the value
# print(my_var) 
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126