Pregunta

Good day to all.

I've been looking for a way to replace items within an array.

Basically I have an array with nested list that looks like that:

array = [ ('a', 'a'), 'c', ('c', 'a'), 'g', 'g', ('h', 'a'), 'a']

Now I'm looking for a way to replace all the appearances of 'a' with 'z'.

and I was hopping to use the following code line in order to achieve that:

new_array = [w.replace('a', 'z') for w in array]
new_array = [ ('z', 'z'), 'c', ('c', 'z'), 'g', 'g', ('h', 'z'), 'a']

Yet, unfortunately I'm receiving the following error:

AttributeError: 'tuple' object has no attribute 'replace'.

I understand the main problem is caused by the use of the tuple (a, x), but they're crucial part of the desired array.

I've spent hours looking for a way around it, And I would highly appreciate any hint in the right direction.

Your help is appreciated!

¿Fue útil?

Solución

def replace(value, find, rep):
    if isinstance(value, tuple):
        return tuple(rep if val==find else val for val in value)
    return value

new_array = [replace(val, 'a', 'z') for val in array]

the last ) should be ].

Otros consejos

  array = [ ('a', 'a'), 'c', ('c', 'a'), 'g', 'g', ('h', 'a'), 'a']
  map(lambda l: tuple(i if i != 'a' else 'z' for i in l)  if isinstance(l, tuple) else l, array) 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top