如何在python中拆分表中的两列

时间:2014-02-18 00:14:47

标签: python python-2.7

有数据表

1 2

1 3

33 34

10 22

11 23

25 26

27 28

.....

现在我需要在两列中拆分数据并将它们合并到一个列表中我在下面编写的代码可以处理单位数字,但不能处理两位或三位数字。

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)

上述数据的此代码输出为

1


2


1


3


3

3


3

4


1

但我需要输出为

1

2

1

3

33

34

11

23

25

26

27

28

2 个答案:

答案 0 :(得分:2)

问题基本上可分为两个阶段:将数字读入包含列表的列表,然后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)

这应该打印出您正在寻找的输出。

答案 1 :(得分:1)

# 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)

<强>输出:

--------------------------------------------------
['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']
--------------------------------------------------