2016-11-27 56 views
-1

我需要將此代碼的打印值存儲到變量中,以便我可以將其轉儲到文本文件中。將for循環的打印值存儲在變量中if else else

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 

我使用列表理解並將其附加到一個變量,但沒有幫助。

+0

如果你不熟悉變量存儲值,你應該看看起來像[Python官方教程]教程(https://docs.python.org/3.5/教程/ index.html中)。 – TigerhawkT3

+0

此外,這個問題中的代碼是從[你以前的問題]的答案(http://stackoverflow.com/questions/40742105/converting-a-text-corpus-to-a-text-document-with -vocabulary-ID和 - 各自-TF)。這個網站不是一個編碼服務;請做一些你自己的工作。 – TigerhawkT3

回答

0

當你做print時,你要求Python將內容傳遞給stdin,即將內容打印到控制檯。如果您想將其存儲在變量中,則需要從print()中刪除內容並存儲在變量中。例如,在您的情況爲:

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)