Do this as a list comprehension?

Mensanator mensanator at aol.com
Fri Jun 6 05:58:46 CEST 2008


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.
>
> 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.
>
> Thanks.

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)]
##>>>



More information about the Python-list mailing list