I see how list comprehensions are good at returning subsets of lists or even across the board remappings if no condition is set. However the filtering conditions will return values in a list that may be smaller than the filtered list. How can I take the positions of the returned values and change those elements conditionally?
Here's a simple example,
>>> v = ['a' , 'b' , 'c' , 'd' , 'f' , 'k' , 'g' , 'a', 'd']
>>> t = ['a', 'k']
How can I modify the elements of v in t to map to new a new value, say 'z', to yield something like
>>> v = ['z' , 'b' , 'c' , 'd' , 'f' , 'z' , 'g' , 'z', 'd']
There's many questions on SO with people coming from Matlab looking to do the equivalent of logical indexing, but mainly just for the purposes of selecting elements and not modifying them inplace as I wish to do. I'd like to do the equivalent of logical indexing for the purposes of modifying filtered elements.
I just found out too that I cannot provide multiple indexes as well to a Python list. I'm using Python 3.
>>> v[ [1,3] ] = 'z'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not list
>>> v[ 1:3 ] = 'z'
>>> v
['a', 'z', 'd', 'f', 'k', 'g', 'a', 'd']
filter works to give me an iterable of the actual objects, but I can't figure out how to modify the elements they point to.
>>> v = ['a' , 'b' , 'c' , 'd' , 'f' , 'k' , 'g' , 'a', 'd']
>>> t = ['a', 'k']
>>> p = filter(lambda x: x in t, v)
>>>
>>> for elem in p :
... print(elem)
...
a
k
a
>>>
>>> for elem in p :
... p = 'z'
...
>>>
>>> for elem in p :
... print(elem)
...
>>>
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire