0

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!

3
  • Python doesn't have arrays as a core data-structure - those are lists. Commented May 10, 2014 at 17:43
  • 1
    Tuples are immutable, either replace the entire tuple or use lists. Commented May 10, 2014 at 17:43
  • why have you tuples and single values in a list? Commented May 10, 2014 at 17:44

2 Answers 2

3
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 ].

Sign up to request clarification or add additional context in comments.

1 Comment

just need to replace ) with ] at the end of new_array = [replace(val, 'a', 'z') for val in array)
2
  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) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.