来自Python docs for itertools.chain:
创建一个迭代器,从第一个可迭代对象中返回元素,直到
它被耗尽,然后继续下一个迭代,直到所有的
可迭代对象已用尽。用于将连续序列视为
单序列。
首先,Python中的一个例子
from itertools import chain
# nested arrays
iterables = [
["one", "two"],
["three", "four"],
["five", "six", "6", ["eight", "nine", "ten"]]
]
list(chain(*iterables))
输出:
['one', 'two', 'three', 'four', 'five', 'six', '6', ['eight', 'nine', 'ten']]
我正在学习 Ruby,因此我尝试使用 Python 文档中的代码示例来复制该行为:
# taken from Python docs as a guide
def chain(*iterables):
# chain('ABC', 'DEF') --> A B C D E F
for it in iterables:
for element in it:
yield element # NOTE! `yield` in Python is not `yield` in Ruby.
# for simplicity's sake think of this `yield` as `return`
我的 Ruby 代码:
def chain(*iterables)
items = []
iterables.each do |it|
it.each do |item|
items << item
end
end
items
end
nested_iterables = [%w[one two], %w[three four], %W[five six #{3 * 2}]]
nested_iterables[2].insert(-1, %w[eight nine ten])
puts chain(*nested_iterables)
# and to enumerate
chain(*nested_iterables).each do |it|
puts it
end
两个输出:
["one", "two", "three", "four", "five", "six", "6", ["eight", "nine", "ten"]]