繁体   English   中英

在Python中的列表项上自定义迭代

[英]Custom Iteration over a list item in Python

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

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

从模式中可以清楚地看出,列表中的第一项是名称,第二项是年龄,第三项是国籍。 迭代它的最有效方法是将for循环中的元素分开。

我是python的新手,并不知道这样做的最佳方法。

for i in len(0, len(my_list):
    name = 
    age = 
    nationality = 

试试这个方便的模式:

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

只需循环3步:

for i in xrange(len(my_list)/3):
    name, age, nationality = my_list[3*i:3*i+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

打印:

0 1 2
3 4 5
6 7 8
9 10 11
12 13 14
15 16 17

如果你需要灵活地对序列进行tuplize,你可以使用:

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 = []

使用zip索引步骤索引(或itertools.izip ):

>>> 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')

这样做的一种方法是:

names = mylist[0::3]
ages = mylist[1::3]
nationalities = mylist[2::3]

然后你可以迭代为

for name in names:
    print name
etc.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM