Python:对列表中包含的列表的每个第n个元素运行一个函数 [英] Python: Run a function of each n-th element of the lists contained in a list
问题描述
在Python中,我们有一个列表列表.例如:
In Python, we have a list of list. For example:
a1 = [[1,4,3,5,6],[6,7,5,3,12],[1,6,4,1,2],[1,9,4,2,1]]
或
a2 = [[4,3,5,6],[6,7,5,12],[1,6,4,2],[1,9,2,1],[3,2,5,11]]
a
的长度和内部列表的长度可能会有所不同.但是所有内部列表始终具有相同的长度.
Both the length of a
and the length of inside lists may vary. But all inside list always have the same length.
我想对由每个列表的第n个元素组成的所有列表应用某些功能.
I'd like to apply some function to all lists made of the n-th element of each list.
例如,考虑 a2
,我想将一个函数迭代地应用到列表[4,6,1,1,3](第一个元素的列表),然后应用到列表[3,7,6,9,2](第二个元素的列表),等等……
Considering a2
for example, I'd like to apply iteratively a function to the list [4,6,1,1,3] (list of first elements), then to the list [3,7,6,9,2] (list of the second elements), etc…
这个想法类似于函数:
map(a2, my_function)
除了my_function不应应用于每个内部列表,而应应用于第n个元素的每个列表.
Except that my_function should not be applied to each inside list but to each list of n-th elements.
希望如此!
执行这种操作的最pythonic方式是什么?
推荐答案
Use zip
with *
operator:
>>> a1 = [[1,4,3,5,6],[6,7,5,3,12],[1,6,4,1,2],[1,9,4,2,1]]
>>> a2 = [[4,3,5,6],[6,7,5,12],[1,6,4,2],[1,9,2,1],[3,2,5,11]]
>>> zip(*a1)
[(1, 6, 1, 1), (4, 7, 6, 9), (3, 5, 4, 4), (5, 3, 1, 2), (6, 12, 2, 1)]
>>> zip(*a2)
[(4, 6, 1, 1, 3), (3, 7, 6, 9, 2), (5, 5, 4, 2, 5), (6, 12, 2, 1, 11)]
>>> map(sum, zip(*a1)) # [1+6+1+1, 4+7+6+9, ...]
[9, 26, 16, 11, 21]
这篇关于Python:对列表中包含的列表的每个第n个元素运行一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!