如何在python中拆分表中的两列
有一个数据表如何在python中拆分表中的两列,python,python-2.7,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
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
这个问题基本上可以分为两个阶段:将数字作为包含列表的列表读入,然后 这将打印出您要查找的输出
# 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']
--------------------------------------------------
您是否尝试使用
np.loadtxt
加载该文件。然后将数据加载为矩阵,我认为这更容易处理。我知道numpy会更容易处理,但我的教授不允许我们使用numpy结构,所以这必须是更简单的方法。。。但是谢谢你的回答…但是你却用numpy标签来标记你的问题。。。
--------------------------------------------------
['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']
--------------------------------------------------