Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python通过分步前进的列表进行迭代_Python_List_Itertools - Fatal编程技术网

Python通过分步前进的列表进行迭代

Python通过分步前进的列表进行迭代,python,list,itertools,Python,List,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

鉴于以下清单:

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 = [('a', '1'), ('b', '2'), ('c', '3'), ('d', '4'),
          ('e', '1'), ('f', '2'), ('g', '3')]
我觉得我应该能够通过使用

output = (list(zip(letters, itertools.cycle(numbers))
但这会产生以下结果:

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 = [('a', '1'), ('b', '2'), ('c', '3'), ('d', '4'),
          ('e', '1'), ('f', '2'), ('g', '3')]

任何帮助都将不胜感激

如果您正在寻找一个无限生成器,您可以对这两个列表使用
cycle
zip
,格式为
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')
...

如果你想要一个有限的元素列表,这应该可以

import itertools

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

list(itertools.islice((zip(itertools.cycle(letters), itertools.cycle(numbers))), max_elems))
导致

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

你希望输出是无限的吗?好问题,它可以是无限的,也可以绑定到for/while循环,我想我最大的困惑是如何让输出列表逐步通过可能性,而不是在最长的列表满足循环()提供的值后终止。可能会添加一个sentinel值no以在无限循环中结束