Python 逐步迭代列表

标签 python list python-itertools

给出以下列表:

letters = ('a', 'b', 'c', 'd', 'e', 'f', 'g')
numbers = ('1', '2', '3', '4')

如何生成一个迭代列表来生成以下内容:

output = [('a', '1'), ('b', '2'), ('c', '3'), ('d', '4'), 
          ('e', '1'), ('f', '2'), ('g', '3'), ('a', '4'),
          ('b', '1'), ('c', '2'), ('d', '3'), ('e', '4'),
          ('f', '1'), ('g', '2')...]

我觉得我应该能够使用

产生所需的输出
output = (list(zip(letters, itertools.cycle(numbers))

但这会产生以下结果:

output = [('a', '1'), ('b', '2'), ('c', '3'), ('d', '4'),
          ('e', '1'), ('f', '2'), ('g', '3')]

任何帮助将不胜感激。

最佳答案

如果您正在寻找无限生成器,则可以将 cyclezip 一起用于两个列表,其形式为 zip(itertools.cycle(x ),itertools.cycle(y))。这将为您提供所需的生成器:

>>> for x in zip(itertools.cycle(letters), itertools.cycle(numbers)):
...     print(x)
...
('a', '1')
('b', '2')
('c', '3')
('d', '4')
('e', '1')
('f', '2')
('g', '3')
('a', '4')
('b', '1')
('c', '2')
('d', '3')
...

关于Python 逐步迭代列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43411381/

相关文章:

python - 属性错误: 'Mob' object has no attribute '_Sprite__g'

Python列表对象没有属性报错

python - For循环不打印项目

python-3.x - 在 Python 3 中创建分层组合?

python - 在 Python 中将 wav 转换为 ogg vorbis

python 创建一个新的 csv 并从列表中填充标题行

python - 如何根据具有特定标识符的选定值(在该组行内)减去一组行

java - 线程安全地从一个列表中删除/添加元素到另一个列表

python - 分割和剥离输出 python

python - itertools 中的 izip_longest : How does rasing IndexError inside the iterator work?