[英]How to iterate for specific elements in a list?
Say I have a large list of tuples, 'a' given as follows: 假设我有一个很大的元组列表,“ 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) ..... ]
For such a list, how do I make another list by iteration and combine the corresponding elements to get the following: 对于这样的列表,如何通过迭代制作另一个列表,并结合相应的元素以获取以下内容:
a = [(0, 10, 20...), (1, 11, 21)....]
Also, lets say I have another list of Arrays, 另外,假设我还有另一个数组列表,
b = [A, B, C, D, E, F, G ,H, I]
So, how would I combine a and b to make another list c such that: 因此,我将如何结合a和b来制作另一个列表c,使得:
c = [A(0,10,20), B(1,11,21) ....]
Thanks! 谢谢!
The first a
list looks like it's been zipped . 第
a
列表看起来像已经压缩了 。 You need to unzip it. 您需要解压缩它。
Like so - 像这样-
>>> 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)]
For the second problem, it seem to be the inverse of the first (Assuming that b
has 'ABC' as characters).So zip them - 对于第二个问题,它似乎是第一个问题的反面(假设
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))]
EDIT 编辑
As suggested by gnibbler in the comments, this method involves upacking of the parameters - (Assuming b
as a complex List) 正如gnibbler在评论中所建议的那样,此方法涉及参数的upack-(假设
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)]
For more clarity over the difference, here is the example with my earlier answer - 为了更清楚地说明两者之间的区别,以下是我先前回答的示例-
>>> 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))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.