Python-将多行转换为一行
我有一个关于我编写的一些python代码的问题:Python-将多行转换为一行,python,function,output,Python,Function,Output,我有一个关于我编写的一些python代码的问题: def read_graph_from_file(filename): txtfile = open(filename, "rU") node_memory = 0 neighbour_list = 0 for entry in txtfile: entry_without_newline = entry.replace('\n',"") columns = entry_without_n
def read_graph_from_file(filename):
txtfile = open(filename, "rU")
node_memory = 0
neighbour_list = 0
for entry in txtfile:
entry_without_newline = entry.replace('\n',"")
columns = entry_without_newline.replace(','," ")
columns = columns.split(" ")
number_of_columns = len(columns)
if number_of_columns == 2:
neighbour_list = columns
neighbour_list.sort()
if node_memory == float(neighbour_list[0]):
y = neighbour_list[1]
print y
我想从中得到的输出是一个列表,即[1,4]。相反,我接收跨多行的字符,即:
一,
四,
我想知道我该如何纠正这一点?如果您想将它们放在列表中,您必须创建一个列表变量,并将结果附加到其中。函数完成后,应返回此列表
def read_graph_from_file(filename):
txtfile = open(filename, "rU")
node_memory = 0
neighbour_list = 0
lst = []
for entry in txtfile:
entry_without_newline = entry.replace('\n',"")
columns = entry_without_newline.replace(','," ")
columns = columns.split(" ")
number_of_columns = len(columns)
if number_of_columns == 2:
neighbour_list = columns
neighbour_list.sort()
if node_memory == float(neighbour_list[0]):
y = neighbour_list[1]
lst.append(y)
return lst
然后,如果您像这样运行函数:
print read_graph_from_file(<fileName>)
或者,您可以在函数末尾直接打印结果列表。这样,您就不必单独使用
print
调用函数来打印y
,这样每次迭代都会产生一行新行。相反,先附加到列表,然后在末尾打印列表。您也可以使用print y、
打印空格而不是换行符,或者累积字符串以指出等等。但是如果您想打印列表,最明显的做法是创建一个列表,如@JesseMu所说。
[1,4]