0

In my Python programming course, we are discussing how to manipulate (add,subtract,etc.) arrays and sub-arrays. An example from class was if we had

ourArray = [['a','b','c'],['e','f','g','h'],['i','j'],['k','l','m','n','o','p']...]

and Array = ['a','e','i','k',...], would something like ourArray-Array be possible?

I tried

for w in ourArray:
    w[0] - Array[0]

In the end, what I would like is

[['a','b','c'],['e','f','g','h'],['i','j'],['k','l','m','n','o','p']...] - ['a','e','i','k',...] = ['b','c'],['f','g','h'],['j'],['l','m','n','o','p']...].

Also, I am using Python 3 in Windows.

1
  • set difference sounds like what you want (but it doenst preserve order...) Commented Feb 3, 2015 at 19:12

2 Answers 2

2

How about this list comprehension, Pythonic, one liner:

>>> ourArray = [['a','b','c'],['e','f','g','h'],['i','j'],['k','l','m','n','o','p']]
>>> Array = ['a','e','i','k']
>>> [[item for item in arr if item not in Array] for arr in ourArray]
[['b', 'c'], ['f', 'g', 'h'], ['j'], ['l', 'm', 'n', 'o', 'p']]

For each array in ourArray, take only the items that are not in Array.

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

Comments

1

You can always do the brute force method

>>> ourArray = [['a','b','c'],['e','f','g','h'],['i','j'],['k','l','m','n','o','p']]
>>> Array = ['a','e','i','k']
>>> for i in ourArray:
...     for j in i:
...          if j in Array:
...                i.remove(j)
... 
>>> ourArray
[['b', 'c'], ['f', 'g', 'h'], ['j'], ['l', 'm', 'n', 'o', 'p']]

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.