gpt4 book ai didi

ruby - 阅读表格的一半

转载 作者:太空宇宙 更新时间:2023-11-03 18:01:37 25 4
gpt4 key购买 nike

当我有一张 table 时;

1 0 0 1 0
0 1 0 1 0
0 0 1 0 1
1 1 1 1 0
0 0 0 0 1

假设我只想读取并保留该表上对角线上的值,我如何才能在纯 ruby​​ 中轻松完成此操作?

这样最终的结构看起来像

1 0 0 1 0
1 0 1 1
1 0 1
1 0
1

谢谢

最佳答案

这假设你的表在某个文件中,但你基本上可以从任何你想开始的地方开始:

# get data from file
data = File.readlines(path).map(&:chomp)

# convert to array of integers
a = data.map { |line| line.split(" ").map(&:to_i) }

# remove incrementally more elements from each row
a.each_index { |index| a[index].slice!(0,index) }

# alternatively, you could set these to nil
# in order to preserve your row/column structure
a.each_index { |index| index.times { |i| a[index][i] = nil } }

关于ruby - 阅读表格的一半,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2996010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com