faqts : Computers : Programming : Languages : Python : Snippets : Lists

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

8 of 9 people (89%) answered Yes
Recently 6 of 7 people (86%) answered Yes


Intersection of multiple lists/lists of lists

Jul 5th, 2000 10:01
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 209, Gordon McMillan

Packages: basic_datatypes.lists
> 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, [])
        tmp[x] = z
rslt = []
for k,v in tmp.items():
    if len(v) == len(ml):
print rslt
# [2]