2016-11-27 53 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)