Can I do this with list comprehension?

B

barberomarcelo

Let's say I have two lists:

a = [0, 1, 0, 1, 1, 0]
b = [2, 4, 6, 8, 10, 12]

I want a list comprehension that has the elements in b where a[element]
== 1.

That's to say, in the example above, the result must be: [4, 8, 10]

Any hints?

Marcelo
 
E

Erik Max Francis

Let's say I have two lists:

a = [0, 1, 0, 1, 1, 0]
b = [2, 4, 6, 8, 10, 12]

I want a list comprehension that has the elements in b where a[element]
== 1.

That's to say, in the example above, the result must be: [4, 8, 10]

Any hints?
>>> from itertools import izip
>>> a = [0, 1, 0, 1, 1, 0]
>>> b = [2, 4, 6, 8, 10, 12]
>>> [y for x, y in izip(a, b) if x == 1]
[4, 8, 10]
 
G

Gabriel Genellina

At said:
a = [0, 1, 0, 1, 1, 0]
b = [2, 4, 6, 8, 10, 12]

I want a list comprehension that has the elements in b where a[element]
== 1.

That's to say, in the example above, the result must be: [4, 8, 10]

print [belem for aelem,belem in zip(a,b) if aelem==1]
print [belem for i,belem in enumerate(b) if a==1]

Or itertools.izip...


Gabriel Genellina
Softlab SRL





__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas
 
D

Dennis Lee Bieber

Let's say I have two lists:

a = [0, 1, 0, 1, 1, 0]
b = [2, 4, 6, 8, 10, 12]

I want a list comprehension that has the elements in b where a[element]
== 1.

That's to say, in the example above, the result must be: [4, 8, 10]

Any hints?
What have you tried?
a = [0, 1, 0, 1, 1, 0]
b = [2, 4, 6, 8, 10, 12]
c = [b[x] for x in xrange(min(len(a), len(b))) if a[x] == 1]
c
[4, 8, 10]
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
B

Ben Finney

Let's say I have two lists:

a = [0, 1, 0, 1, 1, 0]
b = [2, 4, 6, 8, 10, 12]

I want a list comprehension that has the elements in b where a[element]
== 1.

That's to say, in the example above, the result must be: [4, 8, 10]

Any hints?

What have you already tried, and how is it insufficient?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top