Python中对列表项的自定义迭代

2024-06-11 05:04:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python列表,其中包含以下示例内容:

['mark', 29, 'american', 'james', 45, 'british', 'arthur', 76, 'australian']

从模式上可以清楚地看出,清单中的第一项是姓名,第二项是年龄,第三项是国籍。 在一个for循环中循环元素的最有效方法是什么。

我是python新手,不知道最好的方法。

^{pr2}$

Tags: 方法示例内容列表for模式mark姓名
3条回答

实现新类型迭代的最佳方法是编写生成器。它们允许您封装迭代样式并将其与其他代码分开:

def by_threes(seq):
    it = iter(seq)
    while True:
        yield next(it), next(it), next(it)

for a, b, c in by_threes(range(20)):
    print a,b,c

印刷品:

^{pr2}$

如果需要灵活地对序列进行元组化,可以使用以下命令:

def by_chunks(seq, n):
    """Yield lists [a,b,..] from `seq`, each list having `n` elements."""
    l = []
    for i, x in enumerate(seq):
        l.append(x)
        if (i % n) == n-1:
            yield l
            l = []

试试这个方便的模式:

from itertools import izip

iters = [iter(my_list)] * 3   # change 3 to number of items in each group
for name, age, nationality in izip(*iters):
     print name, age, nationality

将步骤索引与^{}(或^{})一起使用:

>>> l = ['mark', 29, 'american', 'james', 45, 'british', 'arthur', 76, 'australian']
>>> for name, age, nationality in zip(l[::3], l[1::3], l[2::3]):
...     print (name, age, nationality)
... 
('mark', 29, 'american')
('james', 45, 'british')
('arthur', 76, 'australian')

相关问题 更多 >