Python 有一个很好的特性:
print([j**2 for j in [2, 3, 4, 5]]) # => [4, 9, 16, 25]
在 Ruby 中更简单:
puts [2, 3, 4, 5].map{|j| j**2}
但如果是关于嵌套循环,Python 看起来更方便。
在 Python 中我们可以这样做:
digits = [1, 2, 3]
chars = ['a', 'b', 'c']
print([str(d)+ch for d in digits for ch in chars if d >= 2 if ch == 'a'])
# => ['2a', '3a']
Ruby 中的等价物是:
digits = [1, 2, 3]
chars = ['a', 'b', 'c']
list = []
digits.each do |d|
chars.each do |ch|
list.push d.to_s << ch if d >= 2 && ch == 'a'
end
end
puts list
Ruby 有类似的东西吗?
最佳答案
Ruby 中常用的方式是适当的组合Enumerable和 Array实现相同的方法:
digits.product(chars).select{ |d, ch| d >= 2 && ch == 'a' }.map(&:join)
这只比列表理解长 4 个左右的字符,并且同样具有表现力(恕我直言,当然,但由于列表理解只是列表 monad 的一种特殊应用,有人可能会争辩说,使用Ruby 的集合方法),同时不需要任何特殊语法。
关于python - Ruby 是否有类似 Python 的列表推导式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11319429/