0

I have a question concerning some python code that I have written:

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

The output I want from this is a list, i.e. [1,4]. Instead I am receiving the characters across multiple lines, i.e:

1

4

I was wondering how I might rectify this?

2
  • 2
    You're printing y individually, which will result in a new line per iteration. Instead, append to a list first, then print the list at the end. Commented Sep 28, 2014 at 2:07
  • You can also use print y, to print a space instead of a newline, or accumulate a string to point out, etc. But if you want to print a list, the obvious thing to do is to create a list, as @JesseMu says. Commented Sep 28, 2014 at 2:19

1 Answer 1

1

If you want them in a list, you will have to create a list variable and just append your results to it. You should return this list once your function is done.

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

Then if you run your function like this:

print read_graph_from_file(<fileName>)

You will get the desired result:

[1,4]

Alternatively, you can print the resulting list directly at the end of your function. Then you won't have to call the function with print.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.