【问题标题】:Ruby reverse iterate array but not indexRuby反向迭代数组但不是索引
【发布时间】:2017-07-06 20:40:51
【问题描述】:

如何将此代码转换为涉及反向数组迭代但不索引的 Ruby?

    out = 0
    for index,x in enumerate(reversed(d)):
        out += x*pow(2,index)

从 Python 代码中我可以理解,数组 d 是反转的,但元素的索引不是?
扭曲!
如何在 Ruby 中做到这一点?

【问题讨论】:

标签: python arrays ruby loops


【解决方案1】:

您的 Python 代码 sn-p 在 Ruby 中的等价物是:

d.reverse_each.with_index.inject(0) do |out, (x,i)|
  out += x * 2**i
end

【讨论】:

    【解决方案2】:

    考虑 Python 中的下一个输出:

    for index, string in enumerate(reversed(['zero', 'one', 'two'])):
        print index, string
    # 0 two
    # 1 one
    # 2 zero
    

    然后您可以在应用枚举器之前使用reverse,在本例中为each,因此,它会将您的数组作为['two', 'one', 'zero'],并且每次迭代的索引将保持不变:

    ['zero', 'one', 'two'].reverse.each_with_index do |word, index|
      puts "#{index} #{word}"
    end
    # 0 two
    # 1 one
    # 2 zero
    

    【讨论】:

    • 使用[...].reverse_each.with_index 会稍微提高性能(我认为?...尚未对其进行基准测试)。
    • reverse_each seems 要慢一些。
    猜你喜欢
    • 2017-07-14
    • 2017-12-23
    • 2014-08-22
    • 2014-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-05
    相关资源
    最近更新 更多