2

with a 2 dimension array which looks like this one:

myarray = [['jacob','mary'],['jack','white'],['fantasy','clothes'],['heat','abc'],['edf','fgc']]

every elements is an array which has fixed length elements. how to become this one,

mylist = ['jacob','mary','jack','white','fantasy','clothes','heat','abc','edf','fgc']

here's my solve

mylist = []
for x in myarray:
   mylist.extend(x)

should be more simple i guess

user2003548
  • 4,287
  • 5
  • 24
  • 32

2 Answers2

9

Use itertools.chain.from_iterable:

from itertools import chain
mylist = list(chain.from_iterable(myarray))

Demo:

>>> from itertools import chain
>>> myarray = [['jacob','mary'],['jack','white'],['fantasy','clothes'],['heat','abc'],['edf','fgc']]
>>> list(chain.from_iterable(myarray))
['jacob', 'mary', 'jack', 'white', 'fantasy', 'clothes', 'heat', 'abc', 'edf', 'fgc']

However, Haidro's sum() solution is faster for your shorter sample:

>>> timeit.timeit('f()', 'from __main__ import withchain as f')
2.858742465992691
>>> timeit.timeit('f()', 'from __main__ import withsum as f')
1.6423718839942012
>>> timeit.timeit('f()', 'from __main__ import withlistcomp as f')
2.0854451240156777

but itertools.chain wins if the input gets larger:

>>> myarray *= 100
>>> timeit.timeit('f()', 'from __main__ import withchain as f', number=25000)
1.6583486960153095
>>> timeit.timeit('f()', 'from __main__ import withsum as f', number=25000)
23.100156371016055
>>> timeit.timeit('f()', 'from __main__ import withlistcomp as f', number=25000)
2.093297885992797
Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
5
>>> myarray = [['jacob','mary'],['jack','white'],['fantasy','clothes'],['heat','abc'],['edf','fgc']]
>>> sum(myarray,[])
['jacob', 'mary', 'jack', 'white', 'fantasy', 'clothes', 'heat', 'abc', 'edf', 'fgc']

Or

>>> [i for j in myarray for i in j]
['jacob', 'mary', 'jack', 'white', 'fantasy', 'clothes', 'heat', 'abc', 'edf', 'fgc']
TerryA
  • 58,805
  • 11
  • 114
  • 143
  • i don't understand why can this line work?sum(myarray,[]),does [] imply this is a list addition?why not sum(myarray,list)? – user2003548 May 01 '13 at 11:16
  • @user2003548 Take a look at the python documentation about the sum function: http://docs.python.org/2/library/functions.html#sum . Pretty much, you iterate through `myarray` and it adds each element into the `start` parameter, here it being `[]`. So `[] + ['jacob','mary'] == ['jacob', 'mary']` and so on for every other element – TerryA May 01 '13 at 11:25
  • @user2003548 I'll try explain it with another example. The default value of the second parameter is `0`. `sum([1,2,3], 0) == 6` (Which is what you would expect normally.) Now, doing `sum([1,2,3], 4)` equals `10`, because you're adding all the values of the list onto 4. – TerryA May 01 '13 at 11:37