2

I've the following two arrays:

array1 = [0, 1, 1, 0]
array2 = ['foo', 'bar', 'hello', 'bye']

I want to save into an array the values of array2 that has the index 1in array1.

On the example above, the desired result should be result_array = ['bar', 'hello'].

I've tried something like this, but it's not working.

for i in array1:
  if i = 1:
     result_array.append(array2[i])

Thanks in advance

3
  • I assume if i = 1: is a typo? Commented Jan 28, 2014 at 10:36
  • You should have pointed out that is not working means throws exception Commented Jan 28, 2014 at 10:39
  • Obligatory comment: Those are not arrays, those are lists. Commented Jan 28, 2014 at 10:50

5 Answers 5

7

The problem with your code is that you're using = in if condition, replace it with ==. And secondly to get the index as well as item you need to use enumerate, currently you're appending array[i], so your code will end up appending 'bar' two times.

>>> result_array = []
>>> for i, x in enumerate(array1):
        if x == 1:
            result_array.append(array2[i])
...         
>>> result_array
['bar', 'hello']

Another better way to do this is to use zip and a list comprehension:

>>> [b for a, b in zip(array1, array2) if a==1]
['bar', 'hello']

And fastest way to do this is to use itertools.compress:

>>> from itertools import compress
>>> list(compress(array2, array1))
['bar', 'hello']
Sign up to request clarification or add additional context in comments.

Comments

2

If you're interested in only the 1s in array 1, then you can use zip to iterate through multiple list/array at the same time, see http://docs.python.org/2/library/functions.html#zip (note that zip will ONLY iterate until the length of the shorter list):

>>> array1 = [0, 1, 1, 0]
>>> array2 = ['foo', 'bar', 'hello', 'bye']
>>> [j for i,j in zip(array1, array2) if i == 1]
['bar', 'hello']

If you want an index of the two arrays using array1 as key in a defaultdict, see http://docs.python.org/2/library/collections.html#collections.defaultdict:

>>> from collections import defaultdict
>>> array1 = [0, 1, 1, 0]
>>> array2 = ['foo', 'bar', 'hello', 'bye']
>>> array3 = defaultdict(list)
>>> for i,j in zip(array1,array2):
...     array3[i].append(j)
... 
>>> array3[1]
['bar', 'hello']
>>> array3[0]
['foo', 'bye']

Comments

2

You can use the built-in zip function and list comprehensions:

print [y for x, y in zip(array1, array2) if x == 1]

Or, if you're into numpy:

>>> import numpy as np
>>> array1 = np.array([0, 1, 1, 0])
>>> array2 = np.array(['foo', 'bar', 'hello', 'bye'])
>>> # np.nonzero returns indices of array1 that are, well, non-zero
>>> array2[np.nonzero(array1)]
array(['bar', 'hello'], 
      dtype='|S5')

Comments

1

The modified version of your code which will work is:

for i in range(len(array1)):
    if array1[i]:
        result_array.append(array2[i])

The problems in your code are:

1) You use for i in array1, where i is the temp iterator created to represent the values in the list. So it will always be either 0 or 1, depending on what value of the list it represents

2) if i=1 is wrong. = is assignment operator and == should be used to compare values. Since you said the list contains only 0s and 1s, if i: us enough

Comments

1
from itertools import izip
res = [v2 for v1, v2 in izip(array1, array2) if v1==1]

You may use simple zip instead of izip for small lists.

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.