Do this as a list comprehension?

Mensanator mensanator at aol.com
Fri Jun 6 13:50:25 EDT 2008


On Jun 6, 1:44 am, "Terry Reedy" <tjre... at udel.edu> wrote:
> "Mensanator" <mensana... at aol.com> wrote in message
>
> news:bbd90051-36be-4378-9a27-2a47a5471d12 at a1g2000hsb.googlegroups.com...
> | On Jun 5, 10:42?pm, John Salerno <johnj... at gmailNOSPAM.com> wrote:
> | > Is it possible to write a list comprehension for this so as to produce
> a
> | > list of two-item tuples?
> | >
> | > base_scores = range(8, 19)
> | > score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3]
> | > print zip(base_scores, score_costs)
> | >
> | > I can't think of how the structure of the list comprehension would work
> | > in this case, because it seems to require iteration over two separate
> | > sequences to produce each item in the tuple.
>
> Which is exactly the purpose of zip, or its specialization enumerate!

Aren't you overlooking the fact that zip() truncates the output
to the shorter length iterable? And since the OP foolishly
hardcoded his range bounds, zip(base_scores,score_cost) will
silently return the wrong answer if the base_count list grows.

Surely enumerate() wasn't added to Python with no intention of
ever being used.


>
> | > zip seems to work fine anyway, but my immediate instinct was to try a
> | > list comprehension (until I couldn't figure out how!). And I wasn't
> sure
> | > if list comps were capable of doing everything a zip could do.
> |
> | base_scores = range(8, 19)
> | score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3]
> | print zip(base_scores, score_costs)
> |
> | s = [(i+8,j) for i,j in enumerate( [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3])]
> | print s
> |
> | ##>>>
> | ##[(8, 0), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15,
> | 2), (16, 2), (17, 3), (18, 3)]
> | ##[(8, 0), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15,
> | 2), (16, 2), (17, 3), (18, 3)]
> | ##>>>
>
> Of course, enumerate(iterable) is just a facade over zip(itertools.count(),
> iterable)

But if all I'm using itertools for is the count() function, why would
I
go to the trouble of importing it when I can simply use enumerate()?

Is it a couple orders of magnitude faster?




More information about the Python-list mailing list