0

I just started python, any suggestions would be greatly appreciated. I'm reading a table generated by another program and pulling out 2 numbers from each line, I'll call them a and b. (they are saved as flux and observed in my program) I need to take these two numbers from each line and format them like this-

(a,b),(a,b),(a,b) ect. 

Each consecutive parenthesis is from the consecutive line, first a,b is from line 1, second a,b is from line 2, etc. I need to read the entire table however, the table length will vary.

This is what I have so far. It can read the table and pull out the numbers I need, however, I don't know how to put the numbers into the proper format. I want to say something recursive would be most efficient but I'm unsure of how to do that. Thank you in advance.

#!/usr/bin/python

file = open("test_m.rdb")

 while 1:
    line = file.readline()
    i = line.split()
    flux = i[2]
    observed = i[4]
    if not line:
        break
1
  • Do you want your data to output to a string or a list? Also, how is the input file structured? Are the two numbers separated by a space on each line, or is it like "(1,6)"? Commented Jun 1, 2012 at 21:43

3 Answers 3

1
with open("test_m.rdb") as inf:
    results = [(i[2],i[4]) for i in (line.split() for line in inf)]

result_string = ",".join(str(res) for res in results)

or a more general formatter:

result_string = ", ".join("('{2}', '{4}')".format(*res) for res in results)
Sign up to request clarification or add additional context in comments.

3 Comments

Do you mean result_string = ",".join([str(res) for res in results])?
@C0deH4cker - Your variant is a list comprehension, which builds a new list in memory and then passes it to join(). I wrote it as a generator expression, which passes values one at a time to join() without building a list. They both work, but mine should be slightly faster and use less memory. See python.org/dev/peps/pep-0289
Ahh, never knew about generator expressions like that before. Good to know, thanks!
0

Very simple solution:

with open('data') as data:
    print ', '.join('(%s, %s)' % (x.split()[2], x.split()[4])
                    for x in data.readlines())

Just use readlines to iterate over the lines in the file.

Comments

0

assuming that two values you got are str1 and str2
//inside a loop which iterates through your values
strTable = strTable + ['('+str1+')','('+str2+')']

hope oit will work, if it dont, comment , i will solve it.

1 Comment

dont worry about commas after one set of value, it will be auto-added when adding list type values.

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.