Python: map in place [duplicate]

风格不统一 提交于 2019-12-06 17:18:23

问题


I was wondering if there is a way to run map on something. The way map works is it takes an iterable and applies a function to each item in that iterable producing a list. Is there a way to have map modify the iterable object itself?


回答1:


A slice assignment is often ok if you need to modify a list in place

mylist[:] = map(func, mylist)



回答2:


It's simple enough to write:

def inmap(f, x):
    for i, v in enumerate(x):
            x[i] = f(v)

a = range(10)
inmap(lambda x: x**2, a)
print a



回答3:


Just write the obvious code to do it.

for i, item in enumerate(sequence):
    sequence[i] = f(item)



回答4:


You can use a lambda (or a def) or better list comprehension (if it is sufficient):

[ do_things_on_iterable for item in iterable ]

Anyway you may want to be more explicit with a for loop if the things become too much complex.

For example you can do something like, that but imho it's ugly:

[ mylist.__setitem__(i,thing) for i,thing in enumerate(mylist) ]


来源:https://stackoverflow.com/questions/3000461/python-map-in-place

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!