由于默认设置zip_longest
不适合您,因此这里有一个更智能的版本:
import pprint
word = 'PROBLEM'
def zip_longest(*iterators):
last = {}
# Make a list of non-empty iterators
non_empty = dict.fromkeys(range(len(iterators)))
# Make sure it's an iterator, does no harm on iterators and helps
# on lists
iterators = map(iter, iterators)
while non_empty:
# Prepare the row
row = []
# Walk through the iterators in the given order
for i, iterator in enumerate(iterators):
# If there are still values, find the next
if i in non_empty:
try:
last[i] = iterator.next()
except StopIteration:
# No items anymore, this one is empty
del non_empty[i]
# Add the current (or last if it was already empty) value
row.append(last.get(i))
yield row
第一个/简单测试:
x = [1]
y = [2]
pprint.pprint(list(zip_longest(word, x, y)))
[['P', 1, 2],
['R', 1, 2],
['O', 1, 2],
['B', 1, 2],
['L', 1, 2],
['E', 1, 2],
['M', 1, 2],
['M', 1, 2]]
稍微复杂一点:
x = range(3)
y = range(6)
pprint.pprint(list(zip_longest(word, x, y)))
[['P', 0, 0],
['R', 1, 1],
['O', 2, 2],
['B', 2, 3],
['L', 2, 4],
['E', 2, 5],
['M', 2, 5],
['M', 2, 5]]
对于其他更长的范围:
x = range(10)
y = range(5)
pprint.pprint(list(zip_longest(word, x, y)))
[['P', 0, 0],
['R', 1, 1],
['O', 2, 2],
['B', 3, 3],
['L', 4, 4],
['E', 5, 4],
['M', 6, 4],
['M', 7, 4],
['M', 8, 4],
['M', 9, 4],
['M', 9, 4]]
为了完整性:
x = []
y = []
pprint.pprint(list(zip_longest(word, x, y)))
[['P', None, None],
['R', None, None],
['O', None, None],
['B', None, None],
['L', None, None],
['E', None, None],
['M', None, None],
['M', None, None]]