Merging lists has made my brain hurt.
Mike C. Fletcher
mcfletch at rogers.com
Wed Oct 2 12:31:44 EDT 2002
This is just off the top of my head, there are probably better ways...
PythonWin 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32.
Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) -
see 'Help/About PythonWin' for further copyright information.
>>> lol = [['aaa', 'bbb', 'ccc'],['bbb', 'ccc', 'ddd'],['ccc', 'ddd',
'eee']]
>>> def common( source ):
... if not source:
... return []
... set = {}
... for item in source[0]:
... set[item] = 1
... for other in source[1:]:
... for item in other:
... if set.has_key( item ):
... set[item] = set[item]+1
... return [ key for (key,value) in set.items() if value == len(source)]
...
>>> common(lol)
['ccc']
>>>
I think Python 2.3 is going to have a sets module (hopefully back ported
to Python 2.2.x eventually) which would probably be a more obvious approach.
HTH,
Mike
Huw Lynes wrote:
> Hi All,
>
> I have a list containing an arbitrary number of other lists. The
> internal lists contain strings. For example
> lol = [
> ['aaa', 'bbb', 'ccc'],
> ['bbb', 'ccc', 'ddd'],
> ['ccc', 'ddd', 'eee']
> ]
>
> I want to merge the three lists into a single list that only contains
> the strings present in all three lists. In the above case I want to end
> up with
> ['ccc']
>
> This has me utterly stumped. Any help is appreciated.The only articles
> about merging strings that I've managed to find so far have been about
> merging strings so that you don't get repeats. Not quite what I'm
> looking for.
>
> Thanks,
> Huw
>
_______________________________________
Mike C. Fletcher
Designer, VR Plumber, Coder
http://members.rogers.com/mcfletch/
More information about the Python-list
mailing list