2

can anybody try to help me to retrieve numbers in Python and each number to an array: I have done the following code, it does the job but it reads 10 as two numbers:

with open("test.dat") as infile:
    for i, line in enumerate(infile):
        if i == 0:
            for x in range(0, len(line)):
                if(line[x] == ' ' or line[x] == "  "):
                    continue

                else:
                    print(x, " " , line[x], ", ")
                    initial_state.append(line[x])

---Results:

  (0, ' ', '1', ', ')
  (2, ' ', '2', ', ')
  (4, ' ', '3', ', ')
  (6, ' ', '4', ', ')
  (8, ' ', '5', ', ')
  (10, ' ', '6', ', ')
  (12, ' ', '7', ', ')
  (14, ' ', '8', ', ')
  (16, ' ', '9', ', ')
  (18, ' ', '1', ', ')
  (19, ' ', '0', ', ')
  (21, ' ', '1', ', ')
  (22, ' ', '1', ', ')
  (24, ' ', '1', ', ')
  (25, ' ', '2', ', ')
  (27, ' ', '1', ', ')
  (28, ' ', '3', ', ')
  (30, ' ', '1', ', ')
  (31, ' ', '4', ', ')
  (33, ' ', '1', ', ')
  (34, ' ', '5', ', ')
  (36, ' ', '0', ', ')
  (37, ' ', '\n', ', ')

index include spaces, please see the line of numbers im trying to add to array

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0

2 Answers 2

1

Use .split() to split all fields by looping through, please see the following code, it should do it

with open("test.dat") as infile:
       for i, line in enumerate(infile):
           if i == 0: # if first line
               field = [field.split(" ") for field in line.split(" ")]

               for x in range(0, len(field)):
                   initial_state_arr.append(field[x])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that's what I am looking for
1

If you are sure each number is separated by a single space why not just split the line and print each element as an array:

with open("test.dat") as infile:
    content = infile.read().split()
    for index, number in enumerate(content):
        print ((index*2, number))

And what is your exact input and expected result? Does the file have multiple spaces between numbers?

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.