简体   繁体   English

如何使用 Python 将文本文件转换为二维数组?

[英]How to convert a text file to 2D array using Python?

I have a text file :我有一个文本文件:

ABCDEFGHIJKL.MN ABCDEFGHIJKL.MN

My Expectation output: AB CD EF GH IJ KL我的期望输出:AB CD EF GH IJ KL

I tried this :
f = open("test.txt", "r")
output_list = []
for rec in f:
    chars = list(rec.strip())
    output_list.append(chars)
    print(chars)

But It return : ['A', 'B', 'C', ....]但它返回:['A', 'B', 'C', ....]

Any Idea, please任何想法,请

Assuming you want to create a 2D array from a text with multiple lines, please try the following:假设您想从多行文本创建一个二维数组,请尝试以下操作:

with open("test.txt", "r") as f:
    output_list = []
    for rec in f.read().splitlines():
        rec = rec[:-3]  # remove 3 last characters
        list = [rec[i:i+2] for i in range(0, len(rec), 2)]
        output_list.append(list)

print output_list

where "test.txt" looks like:其中“test.txt”看起来像:

ABCDEFGHIJKL.MN
OPQRSTUVWX-YZ

and the output:和输出:

[['AB', 'CD', 'EF', 'GH', 'IJ', 'KL'], ['OP', 'QR', 'ST', 'UV', 'WX']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM