将清单中的每三个项目分组在一起-Python [英] Grouping every three items together in list - Python
问题描述
我有一个包含重复模式的列表,即
I have a list consisting of a repeating patterns i.e.
list=['a','1','first','b','2','second','c','3','third','4','d','fourth']`
我不确定此列表会持续多久,可能会很长,但是我想创建重复模式的列表,即连同填充的名称
I am not sure how long this list will be, it could be fairly long, but I want to create list of the repeating patters i.e. along with populated names
list_1=['a','1','first']
list_2=['b','2','second']
list_3=['c','3','third']
..... etc
我可以用来实现这一目标的最好的基本代码(不需要导入模块)是什么?
What is the best, basic code (not requiring import of modules) that I can use to achieve this?
推荐答案
您可以使用 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')]
使用 zip()
避免创建中间列表,如果您有很长的列表,这可能很重要.
Using zip()
avoids creating intermediate lists, which could be important if you have long lists.
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
但是前者虽然有点神秘,但更为笼统.
But the former, while a little more cryptic, is more general.
如果您需要此列表的名称,那么我建议使用字典:
If you need names for this lists then I would suggest using a dictionary:
>>> 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')
这篇关于将清单中的每三个项目分组在一起-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!