【问题标题】:Problems counting rows and columns with no spaces in a matrix计算矩阵中没有空格的行和列的问题
【发布时间】:2022-06-18 02:57:33
【问题描述】:

我正在尝试查找矩阵文件中的行数和列数。矩阵在字符之间没有空格,但有单独的行。下面的示例应该返回 3 行和 5 列,但这并没有发生。

当我打印矩阵时,每行都有 \n 。我想删除它。我试过.split('\n') 但这没有帮助。我之前用逗号分隔的不同数据集运行了这个脚本我在代码中有line.split(','),它可以返回正确的行数和列数,并打印没有\n的矩阵,我是不知道从line.split() 中删除逗号会发生什么变化。

import sys
import numpy


with open(sys.argv[1], "r") as f:

    m = [[char for char in line.split(' ')] for line in f if line.strip('\n') ]    
 
m_size = numpy.shape(m)
print(m)
print("%s, %s" % m_size)

样本数据:

aaaaa
bbbbb
ccccc

输出:

[['aaaaa\n'], ['bbbbb\n'], ['ccccc']]
3, 1, 

【问题讨论】:

  • 你可以统计一行中的字符数来得到列。
  • 在此处发帖时请使用拼写检查器 - 这不是聊天室。

标签: python


【解决方案1】:

IIUC:

with open(sys.argv[1]) as f:
    m = np.array([[char for char in line.strip()] for line in f])
>>> m
array([['a', 'a', 'a', 'a', 'a'],
       ['b', 'b', 'b', 'b', 'b'],
       ['c', 'c', 'c', 'c', 'c']], dtype='<U1')

>>> m.shape
(3, 5)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2013-05-12
    • 2015-07-05
    • 1970-01-01
    • 2011-02-28
    相关资源
    最近更新 更多