MartyMcFly
MartyMcFly

Reputation: 43

Extracting items from List under condition

I have two lists of values:

f=[1,1,1,2,2,2,3,3,3]
x=[10,20,30,40,50,60,70,80,90]

Now I want to extract all items from x, for which the corresponding item in f fulfills the condition

abs(i)=1

So I want to end up with:

1 10
1 20
1 30

My approach so far is:

for i in f:
    if abs(i)==1:
        for j in x:
            print i,j

But this gives me all items of x for every 1 in f:

1 10
1 20
1 30
1 40
1 50
1 60
1 70
1 80
1 90
1 10
1 20
1 30
1 40
1 50
1 60
1 70
1 80
1 90
1 10
1 20
1 30
1 40
1 50
1 60
1 70
1 80
1 90

Does anyone have an idea, which further conditions I have to make?

Upvotes: 2

Views: 541

Answers (5)

Siva Cn
Siva Cn

Reputation: 947

>>> x=[10,20,30,40,50,60,70,80,90]
>>> f=[1,1,1,2,2,2,3,3,3]
>>> 
>>> [ele for i, ele in enumerate(x) if abs(f[i]) == 1]
[10, 20, 30]
>>> 

Upvotes: 0

RageCage
RageCage

Reputation: 740

This is because your loop is printing the entire second list when it finds that abs(i)==1. I would probably do something like this:

for i in range(len(f)):
    try:
        if abs(f[i])==1:
            print f[i], x[i]
    except IndexError: #this means that x ended early
        break

This should give you the output you're looking for.

Upvotes: 0

user2497586
user2497586

Reputation:

Try using this:

 f=[1,1,1,2,2,2,3,3,3]
 x=[10,20,30,40,50,60,70,80,90]
 tot = zip(f, x)
 for z in tot:
  if abs(z[0])==1:
    print z[0], z[1]

It makes use of zip. It's a useful built-in that allows you return lists of tuples given multiple inputs. It kind of works like map() but it has a first argument of None.

Also, it is important to note that they inputs must be of the same length otherwise the extra indices will be left out. For example, if the input is two lists, one of length 4 and one of length 10, the result will be a list of tuples of length 4 and the last 6 elements of the second input left out.

Upvotes: 0

wim
wim

Reputation: 362567

Iterate in pairs using zip

for i,x_ in zip(f,x):
  if abs(i) == 1:
    print i, x_

You might also want to consider using numpy fancy indexing:

>>> import numpy as np
>>> f = np.array(f)
>>> x = np.array(x)
>>> x[abs(f) == 1]
array([10, 20, 30])

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

Use zip:

>>> [(a, b) for a, b in zip(f, x) if abs(a)==1]
[(1, 10), (1, 20), (1, 30)]

zip returns items from the same indexes from all the iterables passed to it.

>>> for a, b in zip(f, x):
...     if abs(a) == 1:
...         print a, b
...         
1 10
1 20
1 30

Or if you just want items from x then itertools.compress can be helpful:

>>> from itertools import compress
>>> list(compress(x, (abs(i)==1 for i in f)))
[10, 20, 30]

Upvotes: 4

Related Questions