如何將此代碼轉換爲涉及顛倒數組迭代而不是索引的Ruby?Ruby反向迭代數組但不索引
out = 0
for index,x in enumerate(reversed(d)):
out += x*pow(2,index)
從我可以從Python代碼瞭解,該陣列d
得到逆轉,但該元素的索引都沒有?
加捻!
如何在Ruby中做到這一點?
如何將此代碼轉換爲涉及顛倒數組迭代而不是索引的Ruby?Ruby反向迭代數組但不索引
out = 0
for index,x in enumerate(reversed(d)):
out += x*pow(2,index)
從我可以從Python代碼瞭解,該陣列d
得到逆轉,但該元素的索引都沒有?
加捻!
如何在Ruby中做到這一點?
考慮在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'。 –
學會了一個新的竅門。現在看起來很容易!謝謝。 – arjun
'reverse_each' [似乎](https://gist.github.com/vnhnhm/d84272d49b2462db862f4efeea809ae7)稍微慢一些。 –
用Ruby Python代碼段相對應的是:
d.reverse_each.with_index.inject(0) do |out, (x,i)|
out += x * 2**i
end
*「數組d是相反的,但元素的索引不是」* - 什麼? – jonrsharpe
是啊!在這裏檢查代碼 - http://galvanist.com/post/53478841501/python-reverse-enumerate – arjun