Bill Kranec wrote:

Hello,

I have a list of lists, for example [ [1,2] , [3,4] ], and I would like to pass all the elements of that list as arguments to a function (for example the intersection of all list elements). Is there a command in regular Python to do this? I would like to avoid the hassle and speed hit of a loop to extract all the list elements.

In the past, I believe I have used something like flatten(list), which was part of Numarray (I think). Am I missing an obvious or clever solution in regular Python?

Thanks for your help!

Bill
_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Well, here's something i put together (works for lists and tuples, ignores strings and dicts):

### Start Code ###
def flatten(sequence):

   def rflat(seq2):
       seq = []
       for entry in seq2:
           if '__contains__' in dir(entry) and \
                        type(entry) != str and \
                        type(entry)!=dict:
               seq.extend([i for i in entry])
           else:
               seq.append(entry)
       return seq

   def seqin(sequence):
       for i in sequence:
           if '__contains__' in dir(i) and \
                        type(i) != str and \
                        type(i) != dict:
               return True
       return False

   seq = sequence[:]
   while seqin(seq):
       seq = rflat(seq)
   return seq
### End Code ###

Tested it on a few different scenarios, all performed as expected:

>>> flatten([1])
[1]
>>> flatten([1,[1]])
[1, 1]
>>> flatten(['ab',1])
['ab', 1]
>>> flatten([10,(34,42),54,'abc'])
[10, 34, 42, 54, 'abc']
>>> flatten([{'abc':[1,2,3]},[{'a':'1'},{'[1,2]':'ab'}]])
[{'abc': [1, 2, 3]}, {'a': '1'}, {'[1,2]': 'ab'}]

Cheers,
Orri
--
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.
_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to