Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #60070
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Subject | Re: zip list, variables |
| Date | 2013-11-20 11:38 +0100 |
| Organization | None |
| References | <31cfb6e8-aa7e-46c2-ae0b-18d0d66e7bed@googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.2958.1384943908.18130.python-list@python.org> (permalink) |
flebber wrote: > If > > c = map(sum, zip([1, 2, 3], [4, 5, 6])) > > c > Out[7]: [5, 7, 9] > > why then can't I do this? > > a = ([1, 2], [3, 4]) > > b = ([5, 6], [7, 8]) > > c = map(sum, zip(a, b)) > --------------------------------------------------------------------------- > TypeError Traceback (most recent call > last) <ipython-input-3-cc046c85514b> in <module>() > ----> 1 c = map(sum, zip(a, b)) > > TypeError: unsupported operand type(s) for +: 'int' and 'list' > > How can I do this legally? You are obscuring the issue with your map-zippery. The initial value of sum() is 0, so if you want to "sum" lists you have to provide a start value, typically an empty list: >>> sum([[1],[2]]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'list' >>> sum([[1],[2]], []) [1, 2] Applying that to your example: >>> def list_sum(items): ... return sum(items, []) ... >>> map(list_sum, zip(a, b)) [[1, 2, 5, 6], [3, 4, 7, 8]] Alternatively, reduce() does not require an initial value: >>> map(functools.partial(reduce, operator.add), zip(a, b)) [[1, 2, 5, 6], [3, 4, 7, 8]] But doing it with a list comprehension is the most pythonic solution here...
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
zip list, variables flebber <flebber.crue@gmail.com> - 2013-11-20 02:06 -0800
Re: zip list, variables Peter Otten <__peter__@web.de> - 2013-11-20 11:38 +0100
Re: zip list, variables Jussi Piitulainen <jpiitula@ling.helsinki.fi> - 2013-11-20 12:45 +0200
Re: zip list, variables flebber <flebber.crue@gmail.com> - 2013-11-20 12:05 -0800
Re: zip list, variables Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-11-21 01:03 +0000
Re: zip list, variables Peter Otten <__peter__@web.de> - 2013-11-21 09:58 +0100
csiph-web