如何迭代列表中的特定元素?

时间:2014-10-06 04:47:12

标签: python list

说我有一大堆元组,' a'给出如下:

a = [(0,1,2,3,4,5,6,7,8,9), (10, 11, 12, 13, 14, 15, 16, 17,18,19), (20,21,22,23,24,25,26,27,28) ..... ]

对于这样的列表,如何通过迭代创建另一个列表并组合相应的元素以获得以下内容:

a = [(0, 10, 20...), (1, 11, 21)....]

另外,假设我有另一个数组列表,

b = [A, B, C, D, E, F, G ,H, I]

那么,我如何将a和b结合起来制作另一个列表c:

c = [A(0,10,20), B(1,11,21) ....]

谢谢!

1 个答案:

答案 0 :(得分:2)

第一个a列表看起来像zipped。你需要解压缩它 像这样 -

>>> a = [(0,1,2,3,4,5,6,7,8,9), (10, 11, 12, 13, 14, 15, 16, 17,18,19), (20,21,22,23,24,25,26,27,28)]
>>> zip(*a)
[(0, 10, 20), (1, 11, 21), (2, 12, 22), (3, 13, 23), (4, 14, 24), (5, 15, 25), (6, 16, 26), (7, 17, 27), (8, 18, 28)]

对于第二个问题,它似乎与第一个问题相反(假设b有' ABC'作为字符)。所以压缩它们 -

>>> a = zip(*a)
>>> b = "ABCDEFGHI"
>>> zip(b,a)
[('A', (0, 10, 20)), ('B', (1, 11, 21)), ('C', (2, 12, 22)), ('D', (3, 13, 23)), ('E', (4, 14, 24)), ('F', (5, 15, 25)), ('G', (6, 16, 26)), ('H', (7, 17, 27)), ('I', (8, 18, 28))]

修改
正如gnibbler在评论中所建议的那样,这种方法涉及对参数的反击 - (假设b为复杂的列表)

>>> b = [[65, 66], [67, 68], [69, 70], [71, 72], [73, 74], [75, 76], [77, 78], [79, 80], [81, 82]]
>>> zip(b, *a)
[([65, 66], 0, 10, 20), ([67, 68], 1, 11, 21), ([69, 70], 2, 12, 22), ([71, 72], 3, 13, 23), ([73, 74], 4, 14, 24), ([75, 76], 5, 15, 25), ([77, 78], 6, 16, 26), ([79, 80], 7, 17, 27), ([81, 82], 8, 18, 28)]

为了更清楚地了解差异,以下是我之前回答的示例 -

>>> zip(b, zip(*a))
[([65, 66], (0, 10, 20)), ([67, 68], (1, 11, 21)), ([69, 70], (2, 12, 22)), ([71, 72], (3, 13, 23)), ([73, 74], (4, 14, 24)), ([75, 76], (5, 15, 25)), ([77, 78], (6, 16, 26)), ([79, 80], (7, 17, 27)), ([81, 82], (8, 18, 28))]