1

I simply want to extract the indices in two list where they equal some string.

Say:

a = ['foo' for _ in range(5)]
a.extend(['bar' for _ in range(5)])  
print(a)
['foo', 'foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar', 'bar']
b = ['foo' for _ in range(3)]
b.extend(['bar' for _ in range(7)])
print(b)
['foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar', 'bar', 'bar', 'bar']

Then I simply want all indices with 'foo' in list a and 'bar' in list b, which should be [3, 4]

index = (a == 'foo') & (b == 'bar')

does not work as it does with e.g numpy arrays. How do I make this work? thanks a lot!!

HansSnah
  • 2,160
  • 4
  • 18
  • 31
  • possible duplicate of [Python - get position in list](http://stackoverflow.com/questions/364621/python-get-position-in-list) – DhruvPathak Dec 20 '14 at 14:36

1 Answers1

4

Iterate with enumerate function, filter out all the elements which are foo and get only their index, like this

>>> [index for index, item in enumerate(a) if item == "foo"]
[0, 1, 2, 3, 4]

After the edit, the question changed drastically. But this solution would work

>>> a = ['foo', 'foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar', 'bar']
>>> b = ['foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar', 'bar', 'bar', 'bar']
>>> [idx for idx, values in enumerate(zip(a, b)) if values == ("foo", "bar")]
[3, 4]
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • Ah, I see, this indeed works. However, my implementation is unfortunately slightly more complicated. I actually have two different lists with the same length and I need to find the indices, where list a matches, say, 'foo' and list b matches 'bar'. I will update my question, but thanks so far! – HansSnah Dec 20 '14 at 14:42
  • Works flawlessly, thanks! Another way I discovered now was to convert the lists to numpy arrays. Then the indexing works as I initially thought it would. – HansSnah Dec 20 '14 at 15:27