问题
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