简体   繁体   English

如何将函数应用于python中列表的每个子列表?

[英]How to apply a function to each sublist of a list in python?

Lets say I have a list like this: 可以说我有一个这样的列表:

list_of_lists = [['how to apply'],['a function'],['to each list?']]

And I have a function let's say I want to apply the F function to each sublist of the F function can compute some score about two lists. 我有一个功能,让我们说我想要的应用F功能于各子列表F功能可以计算约两列出了一些成绩。 How can apply this F function to each list of list_of_lists and return each score in a new list like this: 如何将此F函数应用于list_of_lists每个列表,并在新列表中返回每个分数,如下所示:

new_list = [score_1, score_2, score_3]

I tried with the map function the following: 我尝试了以下map功能:

map(F, list_of_lists).append(new_list)

You can use the builtin map to do this. 您可以使用内置map执行此操作。

So if the function you want to apply is len , you would do: 因此,如果您要应用的函数是len ,您可以:

>>> list_of_lists = [['how to apply'],['a function'],['to each list?']]
>>> map(len, list_of_lists)
[1, 1, 1]

In Python3 , the above returns a map iterator, so you will need an explicit list call: Python3 ,上面返回一个map迭代器,因此你需要一个显式的list调用:

>>> map(len, list_of_lists)
<map object at 0x7f1faf5da208>
>>> list(map(len, list_of_lists))
[1, 1, 1]

If you are looking to write some code for this which has to be compatible in both Python2 and Python3, list comprehensions are the way to go. 如果您希望为此编写一些必须在Python2和Python3中兼容的代码,那么列表推导就是最佳选择。 Something like: 就像是:

[apply_function(item) for item in list_of_lists]

will work in both Python 2 and 3 without any changes. 将在Python 2和3中工作而不做任何更改。

However, if your input list_of_lists is huge, using map in Python3 would make more sense because the iterator will be much faster. 但是,如果您的输入list_of_lists很大,那么在Python3中使用map会更有意义,因为迭代器会更快。

You can use a list comprehension, like this 您可以使用列表推导,如下所示

[function_to_be_done(item) for item in list_of_lists]

For example, 例如,

>>> list_of_lists = [['how to apply'],['a function'],['to each list?']]
>>> [len(item) for item in list_of_lists]
[1, 1, 1]

Note: Though list comprehensions look like a way to apply a function to all the elements, its main purpose is to construct a new list. 注意:虽然列表推导看起来像是将函数应用于所有元素的方法,但其主要目的是构造一个新列表。 So, if you don't want to construct a new list, then just iterate with for loop and call the function. 所以,如果你不想构造一个新的列表,那么只需用for循环迭代并调用该函数。


Apart from that, you can use the map function in Python 2.7, to apply a function to all the elements and construct a list. 除此之外,您可以使用Python 2.7中的map函数将函数应用于所有元素并构造列表。 For example, 例如,

>>> list_of_lists = [['how to apply'],['a function'],['to each list?']]
>>> map(len, list_of_lists)
[1, 1, 1]

But, map returns a map iterator object in Python 3.x. 但是, map在Python 3.x中返回一个map迭代器对象。 So, you need to explicitly convert that to a list, like this 因此,您需要将其显式转换为列表,如下所示

>>> list_of_lists = [['how to apply'],['a function'],['to each list?']]
>>> map(len, list_of_lists)
<map object at 0x7f94026afd30>
>>> list(map(len, list_of_lists))
[1, 1, 1]

You might want to read about, what Guido thinks about map in this post . 你可能想要阅读一下Guido在这篇文章中map看法。

Basically, map would more often demand you to create a new function (mostly people create a lambda function). 基本上, map会更频繁地要求你创建一个新函数(大多数人创建一个lambda函数)。 But in many cases, list comprehension avoids that. 但在许多情况下,列表理解避免了这种情况。

How about 怎么样

[ F(x) for x in list_of_lists ]

which will iterate over list_of_lists, call F with each sublist as an argument, then generate a list of the results. 将迭代list_of_lists,以每个子列表作为参数调用F,然后生成结果列表。

If you want to use the sublists as all the arguments to F you could do it slightly differently as 如果你想使用子列表作为F所有参数,你可以稍微不同地做

[ F(*x) for x in list_of_lists ]

Something that works on arbitrarily nested lists, eg [[1,2],[[5]],[7,[8,[9,11]]]] : 可以在任意嵌套列表上运行的东西,例如[[1,2],[[5]],[7,[8,[9,11]]]]:

def apply_f(a,f):
 if isinstance(a,list):
     return map(lambda t:apply_f(t,f), a)
 else:
     return f(a)

here is an example of running this: 这是运行这个的一个例子:

>>> ll=[[1,2],[[5]],[7,[8,[9,11]]]]
>>> apply_f(ll,lambda t:t**2)
[[1, 4], [[25]], [49, [64, [81, 121]]]]

and here is how to do the same only on selected levels: 以下是如何仅在选定的级别上执行相同的操作:

def apply_f(a,f,depth,levels):
    if isinstance(a,list):
        return map(lambda t:apply_f(t,f,depth+1,levels), a)
    else:
        if depth in levels:
            return f(a)
        else:
            return a

getting eg 得到例如

>>> apply_f(ll,lambda t:t**2, 0, [2,4])
[[1, 4], [[5]], [49, [8, [81, 121]]]]

there are some optimisations to do here, by avoiding passing f and levels around (making the recursive function an inner function in a wrapper, so that it can use f and levels from the outer scope), but that's minor. 这里有一些优化,通过避免传递flevels (使递归函数成为包装器中的内部函数,以便它可以使用外部作用域中的flevels ),但这是次要的。 (Note that this is Python 2, for Python 3 you need to replace map with something else). (请注意,这是Python 2,对于Python 3,您需要用其他东西替换map )。


For a more generic input, the following would do the trick: 对于更通用的输入,以下方法可以解决这个问题:

def apply_f(a,f):
    try: 
       return(f(a))
    except:
       return map(lambda t:apply_f(t,f), a)

So now also the following sort of works: 所以现在还有以下几种作品:

>> apply_f([(1,2),[[5]],[7,(8,[9,11])]],lambda t:t**2)
[[1, 4], [[25]], [49, [64, [81, 121]]]]

(things get slightly rewritten, as map() always produces lists...) (稍微重写的东西,因为map()总是产生列表......)

Map is your friend! 地图是你的朋友! map takes a function and an iterable (list, for example) and applies the function on each element of the list. map接受一个函数和一个iterable(例如list),并在列表的每个元素上应用该函数。

map(len, [['how to apply'],['a function'],['to each list?']]) 

Output 产量

[1, 1, 1]

If you wanted to do more granular calculation on elements of the sublist, you can nest the map: 如果要对子列表的元素进行更精细的计算,可以嵌套映射:

map(lambda x: map(lambda y: y + 1, x), [[1], [1, 2], [1, 2, 3]])

Output 产量

[[2], [2, 3], [2, 3, 4]]

Another possible approach (also from functional programming) are list comprehensions. 另一种可能的方法(也来自函数式编程)是列表推导。 List comprehension is a way of constructing a list from iterable in Python. List comprehension是一种从Python中的iterable构造列表的方法。 The syntax is [element for element in iterable] . 语法是[element for element in iterable] Any computation can be done on the element, so 任何计算都可以在元素上完成,所以

[f(element) for element in iterable]

means that the resulting list will be a list of elements, where each element is the result of function f. 表示结果列表将是元素列表,其中每个元素是函数f的结果。 Like map, list comprehension can be further nested, resulting in a nested element function application. 像map一样,list comprehension可以进一步嵌套,从而产生一个嵌套的元素函数应用程序。

[element + 1 for element in el] for el in [[1], [1, 2], [1, 2, 3]]]

Output 产量

[[2], [2, 3], [2, 3, 4]]

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

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