gpt4 book ai didi

arrays - 选择数组中除当前之外的所有内容

转载 作者:数据小太阳 更新时间:2023-10-29 08:30:38 26 4
gpt4 key购买 nike

a = [1,4,1]
total = []

a.each do |num|
total << a.select {|x| x != num}
end

p total => [[4], [1, 1], [4]]

我希望选择数组中除当前元素之外的所有其他元素。当没有重复时,上面的工作正常,但当有时,输出不正确。在这种情况下,输出应该是:

[[4,1], [1, 1], [1,4]]

我尝试使用 each_with_index 并以索引而不是数字为目标,但遇到了同样的问题。有任何想法吗?除了选择之外的其他东西?

谢谢

最佳答案

我不是一个 Ruby 开发者,如果这不是惯用的,那么抱歉,但请试一试?

a = [1,4,1]

total = a.each_index.map { |index| a[0...index] + a[(index+1)..-1] }

p total

关于arrays - 选择数组中除当前之外的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38132381/

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