简体   繁体   English

将函数映射到子列表python的一部分

[英]Map a function to part of sublist python

I am working in python and I have a list of lists (or could be also an numpy array) like this: 我在python中工作,我有一个列表列表(或者也可以是一个numpy数组),如下所示:

list = [[0, 0, -1], [1, 1, -2], [1, 2, -3], [2, 2, -4]]

I have a function that takes for every sublist the first two elements and gives a result. 我有一个函数,需要为每个子列表的前两个元素提供结果。 Let's assume that the function I am taking about is sum() so what I want to do is 假设我要处理的功能是sum(),所以我想做的是

list1 = [[sum(0, 0), -1], [sum(1, 1), -2], [sum(1, 2), -3], [sum(2, 2), -4]]

and output is 和输出是

list1 = [[0, -1], [2, -2], [3, -3], [4, -4]]

Is there a way to this with map or numpy.vectorize ? 有没有办法通过mapnumpy.vectorize I can already do it as a loop but it is too expensive for my real data. 我已经可以做为循环了,但是对于我的真实数据来说太昂贵了。

Any help, advice? 任何帮助,建议吗?

In case of numpy array you should have the fastest results using vectorization: 如果是numpy数组,则使用矢量化应可获得最快的结果:

In [128]: arr = np.asarray(list)
#Out[128]:
#array([[ 0,  0, -1],
#       [ 1,  1, -2],
#       [ 1,  2, -3],
#       [ 2,  2, -4]])

In [129]: np.vstack((arr[:,0]+arr[:,1], arr[:,2])).T
#Out[129]:
#array([[ 0, -1],
#       [ 2, -2],
#       [ 3, -3],
#       [ 4, -4]])

Could that be 可能是

[(sum(x, y), z) for x, y, z in list]

Or if you insist on using map use itertools.starmap : 或者,如果您坚持使用map使用itertools.starmap

starmap( lambda x, y, z: (x+y, z), list)

?

For your specific example, you could use a list comprehension as follows: 对于您的特定示例,您可以使用列表推导,如下所示:

my_list = [[0, 0, -1], [1, 1, -2], [1, 2, -3], [2, 2, -4]]

answer = [[x + y, z] for x, y, z in my_list]
print(answer)

Output 产量

[[0, -1], [2, -2], [3, -3], [4, -4]]

To apply a more complex generic function to each item in your list, use map : 要将更复杂的泛型函数应用于列表中的每个项目,请使用map

def func(sublist):
    return [sum(sublist[:2]), sublist[-1]]

my_list = [[0, 0, -1], [1, 1, -2], [1, 2, -3], [2, 2, -4]]

answer = map(func, my_list)

By using the function func you can customise your function as desired. 通过使用函数func ,可以根据需要自定义函数。

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

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