使用if else将for循环的打印值存储在变量中

时间:2016-11-27 23:28:14

标签: python machine-learning list-comprehension

我需要将此代码的打印值存储到变量中,以便将其转储到文本文件中。

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

我使用了列表理解并将其附加到变量中但没有帮助。

1 个答案:

答案 0 :(得分: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)