简体   繁体   English

从文本读取输入到二维数组

[英]Reading input from text into 2d array

I have a txt file which has numbers in pyramid format like: 我有一个txt文件,其中包含金字塔格式的数字,例如:

      5
    10 7
  1  3  12

I want to put them into a 2 dimensional array (like a regular matrix). 我想将它们放入二维数组(如规则矩阵)。 I tried the post . 我试过 but I want to add 0 (zero) to all missing positions. 但我想将0(零)添加到所有丢失的位置。 like: 喜欢:

5,0,0
10,7,0
1,3,12

In order to do that i must know the length of the last line to create suitable 2D array. 为此,我必须知道创建合适的2D数组的最后一行的长度。

How can i achieve this? 我怎样才能做到这一点?

There's no way to avoid reading the entire file in order to do what you want since the lines can all have different lengths which means you can't calculate the offset where any of them start (except the first, of course): 没有办法避免读取整个文件以执行所需的操作,因为所有行的长度都可以不同,这意味着您无法计算任何行的起始位置的偏移量(当然,第一个除外):

def last_row_length(filename):
    lastrow = None
    with open(filename, 'r') as f:
        for lastrow in f: pass
    return len(lastrow.split()) if lastrow is not None else 0

lastrowlen = last_row_length('pyramid.txt')
print(lastrowlen)  # -> 3

If you're going to be reading the file to create the 2D array, you should incorporate finding the length of the last line into creating the array so that you don't have to read the file twice. 如果要读取文件以创建2D数组,则应将查找最后一行的长度合并到创建数组中,这样就不必两次读取文件。

I'll assume we don't know beforehand how many lines there are (meaning we don't know how long each side of the matrix is). 我假设我们事先不知道有多少行(这意味着我们不知道矩阵的每一边有多长)。 I'll also assume your file is called file.txt . 我还将假设您的文件名为file.txt

What we want is a running list of lists. 我们想要的是列表的运行列表。 Once we've read the entire file, we can go back and add the trailing zeros. 阅读完整个文件后,我们可以返回并添加尾随零。 Python strings' split() method will be useful here, because with no arguments this method uses whitespace as a separator. Python字符串的split()方法在这里很有用,因为该方法不带任何参数使用空格作为分隔符。 Here's a simple example with your file: 这是文件的一个简单示例:

>>> with open('file.txt') as file:
...     for line in file:
...         print(line.split())
... 
['5']
['10', '7']
['1', '3', '12']

The following code saves each of these lists as elements of a list called rows : 以下代码将这些列表中的每一个另存为称为rows的列表的元素:

rows = []
with open('file.txt') as file:
    for line in file:
        rows.append(line.split())

Now all that's left is to check the length of the last row, add zeros to the end of each list, and print it in the pretty format you wanted. 现在剩下的就是检查最后一行的长度,在每个列表的末尾添加零,然后以所需的漂亮格式打印出来。 Here's the complete solution: 这是完整的解决方案:

rows = []
with open('file.txt') as file:
    for line in file:
        rows.append(line.split())
size = len(rows[-1])
for i in range(len(rows)):
    rows[i] = rows[i] + ['0'] * (size - len(rows[i]))
for row in rows:
    print(','.join(row))

The number of elements of the last line is the number of elements of the first line when you reverse it to read. 当您将其反转阅读时,最后一行的元素数量是第一行的元素数量。

line.rstrip()

Have you ever tried this one? 您曾经尝试过这个吗?

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

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