简体   繁体   English

将 function 应用于列表中的每个元素

[英]Apply function to each element of a list in place

Similar question to Apply function to each element of a list , however the answers to that question (list comprehension or map()) really return a new list to replace the old one. Apply function to each element of a list 的类似问题,但是该问题的答案(列表理解或 map())实际上返回一个新列表来替换旧列表。

I want to do something like this:我想做这样的事情:

for obj in myList:
    obj.count = 0

Obviously I could (and currently do) process the list exactly this way, but I was wondering if there were a construct such as显然我可以(并且目前正在)以这种方式处理列表,但我想知道是否有这样的构造

foreach(lambda obj: obj.count=0, myList)

Obviously I only care about this if the more "pythonic" way is more efficient.显然,如果更“pythonic”的方式更有效,我只关心这个。 My list can have over 100,000 elements, so I want this to be quick.我的列表可以包含超过 100,000 个元素,因此我希望它能够快速完成。

Note that your question is not about replacing elements of a list in-place, but rather mutating an attribute of each element, without replacing the latter.请注意,您的问题不是就地替换列表的元素,而是改变每个元素的属性,而不替换后者。 Your attempt in terms of a for loop is the way to go.您对for循环的尝试是通往 go 的道路。

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

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