如何将功能应用于列表的元素? [英] How to apply function to elements of a list?

查看:94
本文介绍了如何将功能应用于列表的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对列表中的所有元素应用一个函数,但我想实际更改元素(哪些是对象),而不是查看结果。我认为这是使用 map()或列表推导的问题。

I want to apply a function to all elements in the list, but I want to actually change the elements (which are objects), not view results. I think this is the problem with using map() or list comprehensions.

class Thing(object):
    pass

# some collection of things
my_things

# they are all big...

# produces SyntaxError: invalid syntax
[i.size = "big" for i in my_things]

# produces SyntaxError: lambda cannot contain assignment
map(lambda i: i.size="big", [i for i in my_things]) 

# no error, but is it the preferred way?
for i in my_things:
    i.size="big"

什么是这样做吗?

推荐答案

for i in my_things:
    i.size = "big"

您不想既不使用 map 也不使用列表comprehansion,因为它们实际上创建了新的列表。你不需要这个开销,是吗?

You don't want to use neither map nor list comprehansion because they actually create new lists. And you don't need that overhead, do you?

这篇关于如何将功能应用于列表的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆