Intersection of multiple lists/list of lists

Gordon McMillan gmcm at hypernet.com
Tue Oct 5 09:36:23 EDT 1999


Thomas Weholt wrote:

[snip]
> Something like this perhaps :
> 
> for word in sys.argv(1:):
>  words_dict[word] = dyna_list # the result from the dictonary
>  could be a
> lists or a string, containing entries later converted to a list
> 
> But here I need to create a new list-object for each keyword. I
> don`t know how many keywords the user has specified so this has
> to be dynamic. How can I create list-objects like this
> on-the-fly? Can I use a list of lists? It will probably not be
> integers used for entry-ids in the end, more likely strings, or
> lists if this is possible.

A list of lists would do fine.
 
> What I need is a way of making an intersection of this lists, so
> that only entries containing all keywords will be displayed. The
> final product should be a list to iterate, fetching the valid
> entries in another database.

Lots of possibilities. Here's a nice trick exploiting dictionaries:

>>> ml = [[1,2,3],[2,3,4],[1,2,5]]
>>> tmp = {}
>>> for l in ml:
	for x in l:
		z = tmp.get(x, [])
		z.append(1)
		tmp[x] = z
		
>>> rslt = []
>>> for k,v in tmp.items():
	if len(v) == len(ml):
		rslt.append(k)
			
>>> rslt
[2]



- Gordon




More information about the Python-list mailing list