我有一个由重复模式组成的列表,即
list=['a','1','first','b','2','second','c','3','third','4','d','fourth']`
Run Code Online (Sandbox Code Playgroud)
我不确定这个列表会持续多长时间,它可能相当长,但我想创建重复模式列表,即填充名称
list_1=['a','1','first']
list_2=['b','2','second']
list_3=['c','3','third']
..... etc
Run Code Online (Sandbox Code Playgroud)
我可以用来实现这个目标的最佳基本代码(不需要导入模块)是什么?
您可以使用zip()以下方式获取块:
>>> lst = ['a','1','first','b','2','second','c','3','third','4','d','fourth']
>>> list(zip(*[iter(lst)]*3))
[('a', '1', 'first'), ('b', '2', 'second'), ('c', '3', 'third'), ('4', 'd', 'fourth')]
Run Code Online (Sandbox Code Playgroud)
使用zip()避免创建中间列表,如果您有长列表,这可能很重要.
zip(*[iter(lst)]*3) 可以改写:
i = iter(lst) # Create iterable from list
zip(i, i, i) # zip the iterable 3 times, giving chunks of the original list in 3
Run Code Online (Sandbox Code Playgroud)
但前者虽然有点神秘,但更为笼统.
如果您需要此列表的名称,那么我建议使用字典:
>>> d = {'list_{}'.format(i): e for i, e in enumerate(zip(*[iter(lst)]*3), 1)}
>>> d
{'list_1': ('a', '1', 'first'),
'list_2': ('b', '2', 'second'),
'list_3': ('c', '3', 'third'),
'list_4': ('4', 'd', 'fourth')}
>>> d['list_2']
('b', '2', 'second')
Run Code Online (Sandbox Code Playgroud)
尝试这个
chunks = [data[x:x+3] for x in xrange(0, len(data), 3)]
Run Code Online (Sandbox Code Playgroud)
它将制作包含 3 个项目的子列表