[Tutor] newB Q: extracting common elements from 2 lists

Andrei Kulakov ak@silmarill.org
Mon, 24 Jun 2002 13:04:27 -0400


On Mon, Jun 24, 2002 at 06:51:28AM -0700, Stephen Doughty wrote:
> Hi
> 
> I've just discovered the tutor list, I'm hoping to
> learn a lot more about Python by reading other peoples
> querys/answers.
> 
> My question:
> I'm writing an export script for blender and have
> stuck a hitch. I'm trying to work through the problem
> in IDLE, so the examples are from the command line.
> 
> I have two tuples where the values are lists,
> eg :
> >>> xmap
> {1: [1, 3, 5, 7, 9]}
> >>> ymap
> {1: [1, 2, 3, 4, 5]}
> 
> what I want is to extract the common elements of the
> two tuple values and put them in a new tuple 'list'
> 
> like:
> 
> xymap[1] = xmap[1] *something magic here* ymap[1]
> 
> so xymap[1] contains [1,3,5].
> 
> can it be done?  - as tuples or converted to lists and
> done somehow?
> 
> I found that xymap[1] = xmap[1] and ymap[1] just
> combined the list rather than binary anding them (and
> & caused an error).
> 
> Any advice gratefully received.
> 
> Cheers Stephen
>
One way is to do this:

>>> a = [1, 3, 5, 7, 9]
>>> b = [1, 2, 3, 4, 5]
>>> ab = [x for x in a if x in b]
>>> ab
[1, 3, 5]

Or as a loop:
ab = []
for x in a:
	if x in b:
		ab.append(x)

 - Andrei

> 
> 
> 
> __________________________________________________
> Do You Yahoo!?
> Yahoo! - Official partner of 2002 FIFA World Cup
> http://fifaworldcup.yahoo.com
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org