user2014111
user2014111

Reputation: 843

How to split two columns in a table in python

There is table of data

1 2

1 3

33 34

10 22

11 23

25 26

27 28

.....

now I need to split data in the two columns and merge them in to a single list The code I have written below does the job for single digit numbers but not for two or three digit numbers.

myfile = open("karate.txt","r") #read and write to a file 

for line in myfile.read():   # read data in the file
    fields = ' '.join(line.split()) # split columns of table based on space   
    print fields
    rows = map(int,fields) # converting tuple to integer
    data.extend(rows)

The output of this code for the above data is

1


2


1


3


3

3


3

4


1

but I need the output as

1

2

1

3

33

34

11

23

25

26

27

28

Upvotes: 1

Views: 3566

Answers (2)

lightalchemist
lightalchemist

Reputation: 10221

# Method 1
fields = []
with open("testfile.txt") as infile:
    for line in infile:
        fields.extend(line.split())  # Note that the elements are "strings".

print("-" * 50)
print(fields)
print("-" * 50)
print("On separate lines")
print('\n'.join(fields))
print("-" * 50)
print("With lines in between")
print("\n\n".join(fields))
print("-" * 50)

# Method 2
fields = []
with open("testfile.txt") as infile:
    map(lambda line: fields.extend(line.split()), infile)

print("A slightly shorter implementation")
print(fields)
print("-" * 50)

Output:

--------------------------------------------------
['1', '2', '1', '3', '33', '34', '10', '22', '11', '23', '25', '26', '27', '28']
--------------------------------------------------
On separate lines
1
2
1
3
33
34
10
22
11
23
25
26
27
28
--------------------------------------------------
With lines in between
1

2

1

3

33

34

10

22

11

23

25

26

27

28
--------------------------------------------------
A slightly shorter implementation
['1', '2', '1', '3', '33', '34', '10', '22', '11', '23', '25', '26', '27', '28']
--------------------------------------------------

Upvotes: 1

Michael0x2a
Michael0x2a

Reputation: 64118

The problem can essentially be divided into two stages: Read in the numbers as a list containing lists, then flatten the list.

fields = []
with open("text.txt") as f:
    fields = [line.split(' ') for line in f]

print fields
# [(1, 2), (1, 3), (33, 34), (10, 22), ...etc... ]

flattened = [i for tup in fields for i in tup]
print flattened
# [1, 2, 1, 3, 33, 34, 10, 22, 11, 23, ...etc...]

# Print line by line:
print '\n'.join(flattened)

This should print out the output that you're looking for.

Upvotes: 2

Related Questions